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

Add support for multiple @ResponseSchema decorators using oneOf. #58

Merged
merged 6 commits into from
Sep 3, 2020
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
57 changes: 43 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# routing-controllers-openapi

[![Build Status](https://travis-ci.org/epiphone/routing-controllers-openapi.svg?branch=master)](https://travis-ci.org/epiphone/routing-controllers-openapi) [![codecov](https://codecov.io/gh/epiphone/routing-controllers-openapi/branch/master/graph/badge.svg)](https://codecov.io/gh/epiphone/routing-controllers-openapi) [![npm version](https://badge.fury.io/js/routing-controllers-openapi.svg)](https://badge.fury.io/js/routing-controllers-openapi)

Runtime OpenAPI v3 schema generation for [routing-controllers](https://github.com/typestack/routing-controllers).
Expand Down Expand Up @@ -71,9 +72,7 @@ prints out the following specification:
}
},
"summary": "List users",
"tags": [
"Users"
]
"tags": ["Users"]
}
},
"/users/": {
Expand All @@ -99,9 +98,7 @@ prints out the following specification:
}
},
"summary": "Create user",
"tags": [
"Users"
]
"tags": ["Users"]
}
}
}
Expand Down Expand Up @@ -136,12 +133,12 @@ import { validationMetadatasToSchemas } from 'class-validator-jsonschema'
// ...

const schemas = validationMetadatasToSchemas({
refPointerPrefix: '#/components/schemas/'
refPointerPrefix: '#/components/schemas/',
})

const spec = routingControllersToSpec(storage, routingControllerOptions, {
components: { schemas },
info: { title: 'My app', version: '1.2.0' }
info: { title: 'My app', version: '1.2.0' },
})
```

Expand All @@ -154,15 +151,14 @@ import { OpenAPI } from 'routing-controllers-openapi'

@JsonController('/users')
export class UsersController {

@Get('/')
@OpenAPI({
description: 'List all available users',
responses: {
'400': {
description: 'Bad request'
}
}
description: 'Bad request',
},
},
})
listUsers() {
// ...
Expand Down Expand Up @@ -199,7 +195,7 @@ Using `@OpenAPI` on the controller class effectively applies given spec to each

```typescript
@OpenAPI({
security: [{ basicAuth: [] }] // Applied to each method
security: [{ basicAuth: [] }], // Applied to each method
})
@JsonController('/users')
export class UsersController {
Expand All @@ -216,7 +212,6 @@ import { ResponseSchema } from 'routing-controllers-openapi'

@JsonController('/users')
export class UsersController {

@Get('/:id')
@ResponseSchema(User)
getUser() {
Expand Down Expand Up @@ -259,6 +254,40 @@ Note that when using `@ResponseSchema` together with `@JSONSchema`, the outer de
handler() { ... }
```

#### Multiple ResponseSchemas

Multiple ResponseSchemas with different status codes are supported as follows.

```typescript
@ResponseSchema(Response1)
@ResponseSchema(Response2, {statusCode: '400'})
```

In case of multiple ResponseSchemas being registered with the same status code, we resolve them
using the [oneOf](https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/#oneof) operator.

```typescript
@ResponseSchema(Response1)
@ResponseSchema(Response2)
```

will generate

```json
"200": {
"content": {
"application/json":{
"schema": {
"oneOf": [
{$ref: "#/components/schemas/Response1"},
{$ref: "#/components/schemas/Response2"}
]
}
}
}
}
```

## Supported features

- `@Controller`/`@JsonController` base route and default content-type
Expand Down
142 changes: 142 additions & 0 deletions __tests__/decorators.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,37 @@ describe('decorators', () => {
multipleResponseSchemas() {
return
}

@Get('/twoResponseSchemaSameStatusCode')
@ResponseSchema('SuccessObject1')
@ResponseSchema('SuccessObject2')
twoResponseSchemasSameStatusCode() {
return
}

@Get('/threeResponseSchemaSameStatusCode')
@ResponseSchema('SuccessObject1')
@ResponseSchema('SuccessObject2')
@ResponseSchema('SuccessObject3')
threeResponseSchemasSameStatusCode() {
return
}

@Get('/twoResponseSchemaSameStatusCodeWithOneArraySchema')
@ResponseSchema('SuccessObjects1', { isArray: true })
@ResponseSchema('SuccessObject2')
twoResponseSchemaSameStatusCodeWithOneArraySchema() {
return
}

@Get('/fourResponseSchemasMixedStatusCodeWithTwoArraySchemas')
@ResponseSchema('SuccessObjects1', { isArray: true })
@ResponseSchema('CreatedObject2', { statusCode: 201 })
@ResponseSchema('CreatedObjects3', { statusCode: 201, isArray: true})
@ResponseSchema('BadRequestObject4', { statusCode: 400 })
fourResponseSchemasMixedStatusCodeWithTwoArraySchemas() {
return
}
}

@Controller('/usershtml')
Expand Down Expand Up @@ -436,8 +467,119 @@ describe('decorators', () => {
}
})
})

it('applies two @ResponseSchema with same status code', () => {
const operation = getOperation(routes.twoResponseSchemasSameStatusCode, {})
expect(operation.responses).toEqual({
'200': {
content: {
'application/json': {
schema: {
oneOf: [
{$ref: '#/components/schemas/SuccessObject1'},
{$ref: '#/components/schemas/SuccessObject2'},
]
}
}
},
description: ''
}
})
})

it('applies three @ResponseSchema with same status code', () => {
const operation = getOperation(routes.threeResponseSchemasSameStatusCode, {})
expect(operation.responses).toEqual({
'200': {
content: {
'application/json': {
schema: {
oneOf: [
{$ref: '#/components/schemas/SuccessObject1'},
{$ref: '#/components/schemas/SuccessObject2'},
{$ref: '#/components/schemas/SuccessObject3'},
]
}
}
},
description: ''
}
})
})

it('applies two @ResponseSchema with same status code, where one of them is an array', () => {
const operation = getOperation(routes.twoResponseSchemaSameStatusCodeWithOneArraySchema, {})
expect(operation.responses).toEqual({
'200': {
content: {
'application/json': {
schema: {
oneOf: [
{
items: {
$ref: '#/components/schemas/SuccessObjects1'
},
type: 'array'
},
{$ref: '#/components/schemas/SuccessObject2'},
]
}
}
},
description: ''
}
})
})

it('applies four @ResponseSchema with mixed status code, where two of them are arrays', () => {
const operation = getOperation(routes.fourResponseSchemasMixedStatusCodeWithTwoArraySchemas, {})
expect(operation.responses).toEqual({
'200': {
content: {
'application/json': {
schema: {
items: {
$ref: '#/components/schemas/SuccessObjects1'
},
type: 'array'
}
}
},
description: ''
},
'201': {
content: {
'application/json': {
schema: {
oneOf: [
{$ref: '#/components/schemas/CreatedObject2'},
{
items: {
$ref: '#/components/schemas/CreatedObjects3'
},
type: 'array'
}
]
}
}
},
description: ''
},
'400': {
content: {
'application/json': {
schema: {
$ref: '#/components/schemas/BadRequestObject4'
}
}
},
description: ''
}
})
})
})


describe('@OpenAPI-decorated class', () => {
let routes: { [method: string]: IRoute }

Expand Down
21 changes: 21 additions & 0 deletions src/decorators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,27 @@ export function ResponseSchema(
},
}

const oldSchema =
source.responses[statusCode]?.content[contentType].schema

if (oldSchema?.$ref || oldSchema?.items || oldSchema?.oneOf) {
// case where we're adding multiple schemas under single statuscode/contentType
const newStatusCodeResponse = _.merge(
{},
source.responses[statusCode],
responses[statusCode]
)
const newSchema = oldSchema.oneOf
? {
oneOf: [...oldSchema.oneOf, schema],
}
: { oneOf: [oldSchema, schema] }

newStatusCodeResponse.content[contentType].schema = newSchema
source.responses[statusCode] = newStatusCodeResponse
return source
}

return _.merge({}, source, { responses })
}

Expand Down