Skip to content

Commit eca13eb

Browse files
committed
Update docs
1 parent ea9551c commit eca13eb

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

README.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,62 @@ class ExampleController @Autowired()(openAPIModelRegistration: OpenAPIModelRegis
159159
}
160160
```
161161

162+
### Adding support for custom types
163+
To add support for custom types (or overwrite handling of any type supported by the library)
164+
one can create a custom `ExtraTypesHandler` and provide it when creating a `Bundle`.
165+
166+
There are multiple ways to do so, the simplest is to use `ExtraTypesHandling.simpleMapping`, for example:
167+
```scala
168+
OpenAPIModelRegistration.ExtraTypesHandling.simpleMapping {
169+
case t if t =:= typeOf[JsValue] =>
170+
val schema = new Schema
171+
schema.setType("string")
172+
schema.setFormat("json")
173+
schema
174+
}
175+
```
176+
This `ExtraTypesHandler` handles `JsValue` by mapping it to simple OpenAPI `string` type with `json` format.
177+
178+
But `ExtraTypesHandler` can also be much more powerful, for example:
179+
```scala
180+
case class CustomClassComplexChild(a: Option[Int])
181+
182+
class CustomClass(val complexChild: CustomClassComplexChild) {
183+
// these won't be included
184+
val meaningOfLife: Int = 42
185+
val alphabetHead: String = "abc"
186+
}
187+
188+
...
189+
190+
val extraTypesHandler: ExtraTypesHandler = (tpe: Type) =>
191+
tpe match {
192+
case t if t =:= typeOf[CustomClass] =>
193+
val childTypesToBeResolvedByTheLibrary = Set(typeOf[CustomClassComplexChild])
194+
195+
val handleFn: HandleFn = (resolvedChildTypes, context) => {
196+
val name = "CustomClass"
197+
val customClassComplexChildResolvedSchema = resolvedChildTypes(typeOf[CustomClassComplexChild])
198+
val schema = new Schema
199+
schema.addProperty("complexChild", customClassComplexChildResolvedSchema)
200+
context.components.addSchemas(name, schema)
201+
val schemaReference = new Schema
202+
schemaReference.set$ref(s"#/components/schemas/$name")
203+
schemaReference
204+
}
205+
206+
(childTypesToBeResolvedByTheLibrary, handleFn)
207+
}
208+
```
209+
This `ExtraTypesHandler` handles `CustomClass`.
210+
`CustomClass` uses `CustomClassComplexChild`,
211+
so the handler requests the library to resolve its type (`childTypesToBeResolvedByTheLibrary`).
212+
This resolved type is available as input to `HandleFn`.
213+
Then, in `handleFn`, the handler creates a `Schema` object for `CustomClass`,
214+
adds it to `Components` so that it can be referenced by name `CustomClass`,
215+
and returns reference to that object.
216+
217+
162218
## Examples
163219

164220
### Simple example for springdoc-openapi-scala-1

0 commit comments

Comments
 (0)