Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: customize def-0 model name #459

Merged
merged 2 commits into from
Sep 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 40 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,13 +211,14 @@ An example of using `fastify-swagger` with `static` mode enabled can be found [h
| hideUntagged | false | If `true` remove routes without tags from resulting Swagger/OpenAPI schema file. |
| initOAuth | {} | Configuration options for [Swagger UI initOAuth](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/). |
| openapi | {} | [OpenAPI configuration](https://swagger.io/specification/#oasObject). |
| routePrefix | '/documentation' | Overwrite the default Swagger UI route prefix. |
| routePrefix | '/documentation' | Overwrite the default Swagger UI route prefix. |
| staticCSP | false | Enable CSP header for static resources. |
| stripBasePath | true | Strips base path from routes in docs. |
| swagger | {} | [Swagger configuration](https://swagger.io/specification/v2/#swaggerObject). |
| transform | null | Transform method for schema. |
| transformStaticCSP | undefined | Synchronous function to transform CSP header for static resources if the header has been previously set. |
| uiConfig | {} | Configuration options for [Swagger UI](https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md). Must be literal values, see [#5710](https://github.com/swagger-api/swagger-ui/issues/5710).|
| transformStaticCSP | undefined | Synchronous function to transform CSP header for static resources if the header has been previously set. |
| uiConfig | {} | Configuration options for [Swagger UI](https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md). Must be literal values, see [#5710](https://github.com/swagger-api/swagger-ui/issues/5710).|
| refResolver | {} | Option to manage the `$ref`s of your application's schemas. Read the [`$ref` documentation](#register.options.refResolver) |

If you set `exposeRoute` to `true` the plugin will expose the documentation with the following APIs:

Expand Down Expand Up @@ -255,6 +256,32 @@ fastify.register(require('fastify-swagger'), {
}
```

<a name="register.options.refResolver"></a>
#### Managing your `$ref`s

When this plugin is configured as `dynamic` mode, it will resolve all `$ref`s in your application's schemas.
This process will create an new in-line schema that is going to reference itself.

This logic step is done to make sure that the generated documentation is valid, otherwise the Swagger UI will try to fetch the schemas from the server or the network and fail.

By default, this option will resolve all `$ref`s renaming them to `def-${counter}`, but your view models keep the original `$id` naming thanks to the [`title` parameter](https://swagger.io/docs/specification/2-0/basic-structure/#metadata).

To customize this logic you can pass a `refResolver` option to the plugin:

```js
fastify.register(require('fastify-swagger'), {
swagger: { ... },
...
refResolver: {
buildLocalReference (json, baseUri, fragment, i) {
return json.$id || `my-fragment-${i}`
}
}
}
```

To deep down the `buildLocalReference` arguments, you may read the [documentation](https://github.com/Eomm/json-schema-resolver#usage-resolve-one-schema-against-external-schemas).

<a name="route.options"></a>
### Route options

Expand Down Expand Up @@ -637,8 +664,11 @@ You can integration this plugin with ```fastify-helmet``` with some little work.
})
```

<a name="development"></a>
### Development
<a name="usage"></a>
## `$id` and `$ref` usage


## Development
In order to start development run:
```
npm i
Expand All @@ -647,11 +677,14 @@ npm run prepare

So that [swagger-ui](https://github.com/swagger-api/swagger-ui) static folder will be generated for you.

#### How it works under the hood
### How it works under the hood

`fastify-static` serves `swagger-ui` static files, then calls `/docs/json` to get the Swagger file and render it.

<a name="acknowledgements"></a>
#### How to work with $refs

The `/docs/json` endpoint in dynamic mode produces a single `swagger.json` file resolving all your

## Acknowledgements

This project is kindly sponsored by:
Expand Down
53 changes: 23 additions & 30 deletions examples/dynamic-swagger.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,31 +25,37 @@ fastify.register(require('../index'), {
exposeRoute: true
})

fastify.addSchema({
$id: 'user',
type: 'object',
properties: {
id: {
type: 'string',
description: 'user id'
}
}
})

fastify.addSchema({
$id: 'some',
type: 'object',
properties: {
some: { type: 'string' }
}
})

fastify.put('/some-route/:id', {
schema: {
description: 'post some data',
tags: ['user', 'code'],
summary: 'qwerty',
security: [{ apiKey: [] }],
params: {
type: 'object',
properties: {
id: {
type: 'string',
description: 'user id'
}
}
},
params: { $ref: 'user#' },
body: {
type: 'object',
properties: {
hello: { type: 'string' },
obj: {
type: 'object',
properties: {
some: { type: 'string' }
}
}
obj: { $ref: 'some#' }
}
},
response: {
Expand All @@ -69,25 +75,12 @@ fastify.post('/some-route/:id', {
description: 'post some data',
summary: 'qwerty',
security: [{ apiKey: [] }],
params: {
type: 'object',
properties: {
id: {
type: 'string',
description: 'user id'
}
}
},
params: { $ref: 'user#' },
body: {
type: 'object',
properties: {
hello: { type: 'string' },
obj: {
type: 'object',
properties: {
some: { type: 'string' }
}
}
obj: { $ref: 'some#' }
}
},
response: {
Expand Down
14 changes: 11 additions & 3 deletions lib/mode/dynamic.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,26 @@
const { addHook, resolveSwaggerFunction } = require('../util/common')

module.exports = function (fastify, opts, done) {
const { routes, Ref } = addHook(fastify)

opts = Object.assign({}, {
exposeRoute: false,
hiddenTag: 'X-HIDDEN',
hideUntagged: false,
stripBasePath: true,
openapi: null,
swagger: {},
transform: null
transform: null,
refResolver: {
buildLocalReference (json, baseUri, fragment, i) {
if (!json.title && json.$id) {
json.title = json.$id
}
return `def-${i}`
}
}
}, opts)

const { routes, Ref } = addHook(fastify, opts)

if (opts.exposeRoute === true) {
const prefix = opts.routePrefix || '/documentation'
const uiConfig = opts.uiConfig || {}
Expand Down
9 changes: 6 additions & 3 deletions lib/util/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const Ref = require('json-schema-resolver')
const { rawRequired } = require('../symbols')
const { xConsume } = require('../constants')

function addHook (fastify) {
function addHook (fastify, pluginOptions) {
const routes = []
const sharedSchemasMap = new Map()

Expand Down Expand Up @@ -35,8 +35,11 @@ function addHook (fastify) {
routes,
Ref () {
const externalSchemas = Array.from(sharedSchemasMap.values())
// TODO: hardcoded applicationUri is not a ideal solution
return Ref({ clone: true, applicationUri: 'todo.com', externalSchemas })
return Ref(Object.assign(
{ applicationUri: 'todo.com' },
pluginOptions.refResolver,
{ clone: true, externalSchemas })
)
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
"fastify-plugin": "^3.0.0",
"fastify-static": "^4.0.0",
"js-yaml": "^4.0.0",
"json-schema-resolver": "^1.2.0",
"json-schema-resolver": "^1.3.0",
"openapi-types": "^9.1.0"
},
"standard": {
Expand Down
22 changes: 21 additions & 1 deletion test/spec/openapi/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -308,5 +308,25 @@ test('support global schema reference', async t => {

const swaggerObject = fastify.swagger()
const api = await Swagger.validate(swaggerObject)
t.same(api.components.schemas['def-0'], schema)
t.match(api.components.schemas['def-0'], schema)
})

test('support global schema reference with title', async t => {
const schema = {
title: 'schema view title',
type: 'object',
properties: {
hello: { type: 'string' }
},
required: ['hello']
}
const fastify = Fastify()
fastify.register(fastifySwagger, { openapi: true, routePrefix: '/docs', exposeRoute: true })
fastify.addSchema({ ...schema, $id: 'requiredUniqueSchema' })
fastify.get('/', { schema: { query: { $ref: 'requiredUniqueSchema' } } }, () => {})
await fastify.ready()

const swaggerObject = fastify.swagger()
const api = await Swagger.validate(swaggerObject)
t.match(api.components.schemas['def-0'], schema)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why would this schema, which was added with an $id, not longer show the id via the api?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is explained in the first post of this pr

})