@nestjs/swagger
Version:
OpenAPI for NestJS: generate the API document from controllers and decorators, serve Swagger UI, and derive request types with mapped types.
81 lines (80 loc) • 2.92 kB
JavaScript
import omit from 'es-toolkit/compat/omit';
import pick from 'es-toolkit/compat/pick';
import { getSchemaPath } from '../utils/index.js';
import { wrapRefInAllOf } from '../utils/wrap-ref-in-all-of.util.js';
import { MimetypeContentWrapper } from './mimetype-content-wrapper.js';
export class ResponseObjectMapper {
constructor() {
this.mimetypeContentWrapper = new MimetypeContentWrapper();
}
toArrayRefObject(response, name, produces) {
const exampleKeys = ['example', 'examples'];
const arraySchema = {
type: 'array',
items: { $ref: getSchemaPath(name) }
};
const schema = response.nullable
? { ...arraySchema, nullable: true }
: arraySchema;
return {
...omit(response, [...exampleKeys, 'nullable']),
...this.mimetypeContentWrapper.wrap(produces, {
schema,
...pick(response, exampleKeys)
})
};
}
toRefObject(response, name, produces) {
const exampleKeys = ['example', 'examples'];
const ref = { $ref: getSchemaPath(name) };
const schema = response.nullable ? this.toNullableSchema(ref) : ref;
return {
...omit(response, [...exampleKeys, 'nullable']),
...this.mimetypeContentWrapper.wrap(produces, {
schema,
...pick(response, exampleKeys)
})
};
}
wrapSchemaWithContent(response, produces, schemas) {
if (!response.schema &&
!('example' in response) &&
!('examples' in response)) {
return omit(response, ['nullable']);
}
const exampleKeys = ['example', 'examples'];
const content = this.mimetypeContentWrapper.wrap(produces, {
schema: response.nullable && response.schema
? this.toNullableSchema(response.schema, schemas)
: response.schema,
...pick(response, exampleKeys)
});
const keysToOmit = [...exampleKeys, 'schema', 'nullable'];
return {
...omit(response, keysToOmit),
...content
};
}
toNullableSchema(schema, schemas) {
if (!('$ref' in schema)) {
return { ...schema, nullable: true };
}
const wrapped = wrapRefInAllOf({
...schema,
nullable: true
});
if (wrapped.type !== undefined ||
!this.mayBeObjectRef(schema.$ref, schemas)) {
return wrapped;
}
const { allOf, ...rest } = wrapped;
return { ...rest, type: 'object', allOf };
}
mayBeObjectRef($ref, schemas) {
const prefix = getSchemaPath('');
const target = $ref.startsWith(prefix)
? schemas?.[$ref.slice(prefix.length)]
: undefined;
return !target || target.type === 'object';
}
}