|
| 1 | +import camelCase from 'camelcase'; |
| 2 | +// @ts-ignore |
| 3 | +import cloneDeepWith from 'lodash.clonedeepwith'; |
| 4 | + |
| 5 | +import { ClassType } from '@deepkit/core'; |
| 6 | +import { RouteClassControllerAction, RouteConfig, parseRouteControllerAction } from '@deepkit/http'; |
| 7 | +import { ScopedLogger } from '@deepkit/logger'; |
| 8 | +import { ReflectionKind } from '@deepkit/type'; |
| 9 | + |
| 10 | +import { OpenApiControllerNameConflict, OpenApiOperationNameConflict, TypeError } from './errors'; |
| 11 | +import { ParametersResolver } from './parameters-resolver'; |
| 12 | +import { SchemaKeyFn, SchemaRegistry } from './schema-registry'; |
| 13 | +import { resolveTypeSchema } from './type-schema-resolver'; |
| 14 | +import { |
| 15 | + HttpMethod, |
| 16 | + OpenAPI, |
| 17 | + OpenAPIResponse, |
| 18 | + Operation, |
| 19 | + ParsedRoute, |
| 20 | + RequestMediaTypeName, |
| 21 | + Responses, |
| 22 | + Schema, |
| 23 | + Tag, |
| 24 | +} from './types'; |
| 25 | +import { resolveOpenApiPath } from './utils'; |
| 26 | + |
| 27 | +export class OpenAPICoreConfig { |
| 28 | + customSchemaKeyFn?: SchemaKeyFn; |
| 29 | + contentTypes?: RequestMediaTypeName[]; |
| 30 | +} |
| 31 | + |
| 32 | +export class OpenAPIDocument { |
| 33 | + schemaRegistry = new SchemaRegistry(this.config.customSchemaKeyFn); |
| 34 | + |
| 35 | + operations: Operation[] = []; |
| 36 | + |
| 37 | + tags: Tag[] = []; |
| 38 | + |
| 39 | + errors: TypeError[] = []; |
| 40 | + |
| 41 | + constructor( |
| 42 | + private routes: RouteConfig[], |
| 43 | + private log: ScopedLogger, |
| 44 | + private config: OpenAPICoreConfig = {}, |
| 45 | + ) {} |
| 46 | + |
| 47 | + getControllerName(controller: ClassType) { |
| 48 | + // TODO: Allow customized name |
| 49 | + return camelCase(controller.name.replace(/Controller$/, '')); |
| 50 | + } |
| 51 | + |
| 52 | + registerTag(controller: ClassType) { |
| 53 | + const name = this.getControllerName(controller); |
| 54 | + const newTag = { |
| 55 | + __controller: controller, |
| 56 | + name, |
| 57 | + }; |
| 58 | + const currentTag = this.tags.find(tag => tag.name === name); |
| 59 | + if (currentTag) { |
| 60 | + if (currentTag.__controller !== controller) { |
| 61 | + throw new OpenApiControllerNameConflict(controller, currentTag.__controller, name); |
| 62 | + } |
| 63 | + } else { |
| 64 | + this.tags.push(newTag); |
| 65 | + } |
| 66 | + |
| 67 | + return newTag; |
| 68 | + } |
| 69 | + |
| 70 | + getDocument(): OpenAPI { |
| 71 | + for (const route of this.routes) { |
| 72 | + this.registerRouteSafe(route); |
| 73 | + } |
| 74 | + |
| 75 | + const openapi: OpenAPI = { |
| 76 | + openapi: '3.0.3', |
| 77 | + info: { |
| 78 | + title: 'OpenAPI', |
| 79 | + contact: {}, |
| 80 | + license: { name: 'MIT' }, |
| 81 | + version: '0.0.1', |
| 82 | + }, |
| 83 | + servers: [], |
| 84 | + paths: {}, |
| 85 | + components: {}, |
| 86 | + }; |
| 87 | + |
| 88 | + for (const operation of this.operations) { |
| 89 | + const openApiPath = resolveOpenApiPath(operation.__path); |
| 90 | + |
| 91 | + if (!openapi.paths[openApiPath]) { |
| 92 | + openapi.paths[openApiPath] = {}; |
| 93 | + } |
| 94 | + openapi.paths[openApiPath][operation.__method as HttpMethod] = operation; |
| 95 | + } |
| 96 | + |
| 97 | + for (const [key, schema] of this.schemaRegistry.store) { |
| 98 | + openapi.components.schemas = openapi.components.schemas ?? {}; |
| 99 | + openapi.components.schemas[key] = { |
| 100 | + ...schema.schema, |
| 101 | + __isComponent: true, |
| 102 | + }; |
| 103 | + } |
| 104 | + |
| 105 | + return openapi; |
| 106 | + } |
| 107 | + |
| 108 | + serializeDocument(): OpenAPI { |
| 109 | + // @ts-ignore |
| 110 | + return cloneDeepWith(this.getDocument(), c => { |
| 111 | + if (c && typeof c === 'object') { |
| 112 | + if (c.__type === 'schema' && c.__registryKey && !c.__isComponent) { |
| 113 | + const ret = { |
| 114 | + $ref: `#/components/schemas/${c.__registryKey}`, |
| 115 | + }; |
| 116 | + |
| 117 | + if (c.nullable) { |
| 118 | + return { |
| 119 | + nullable: true, |
| 120 | + allOf: [ret], |
| 121 | + }; |
| 122 | + } |
| 123 | + |
| 124 | + return ret; |
| 125 | + } |
| 126 | + |
| 127 | + for (const key of Object.keys(c)) { |
| 128 | + // Remove internal keys. |
| 129 | + if (key.startsWith('__')) delete c[key]; |
| 130 | + } |
| 131 | + } |
| 132 | + }); |
| 133 | + } |
| 134 | + |
| 135 | + registerRouteSafe(route: RouteConfig) { |
| 136 | + try { |
| 137 | + this.registerRoute(route); |
| 138 | + } catch (err: any) { |
| 139 | + this.log.error(`Failed to register route ${route.httpMethods.join(',')} ${route.getFullPath()}`, err); |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + registerRoute(route: RouteConfig) { |
| 144 | + if (route.action.type !== 'controller') { |
| 145 | + throw new Error('Sorry, only controller routes are currently supported!'); |
| 146 | + } |
| 147 | + |
| 148 | + const controller = route.action.controller; |
| 149 | + const tag = this.registerTag(controller); |
| 150 | + const parsedRoute = parseRouteControllerAction(route); |
| 151 | + |
| 152 | + for (const method of route.httpMethods) { |
| 153 | + const parametersResolver = new ParametersResolver( |
| 154 | + parsedRoute, |
| 155 | + this.schemaRegistry, |
| 156 | + this.config.contentTypes, |
| 157 | + ).resolve(); |
| 158 | + this.errors.push(...parametersResolver.errors); |
| 159 | + |
| 160 | + const responses = this.resolveResponses(route); |
| 161 | + |
| 162 | + if (route.action.type !== 'controller') { |
| 163 | + throw new Error('Only controller routes are currently supported!'); |
| 164 | + } |
| 165 | + |
| 166 | + const slash = route.path.length === 0 || route.path.startsWith('/') ? '' : '/'; |
| 167 | + |
| 168 | + const operation: Operation = { |
| 169 | + __path: `${route.baseUrl}${slash}${route.path}`, |
| 170 | + __method: method.toLowerCase(), |
| 171 | + tags: [tag.name], |
| 172 | + operationId: camelCase([method, tag.name, route.action.methodName]), |
| 173 | + parameters: parametersResolver.parameters.length > 0 ? parametersResolver.parameters : undefined, |
| 174 | + requestBody: parametersResolver.requestBody, |
| 175 | + responses, |
| 176 | + description: route.description, |
| 177 | + summary: route.name, |
| 178 | + }; |
| 179 | + |
| 180 | + if (this.operations.find(p => p.__path === operation.__path && p.__method === operation.__method)) { |
| 181 | + throw new OpenApiOperationNameConflict(operation.__path, operation.__method); |
| 182 | + } |
| 183 | + |
| 184 | + this.operations.push(operation); |
| 185 | + } |
| 186 | + } |
| 187 | + |
| 188 | + resolveResponses(route: RouteConfig) { |
| 189 | + const responses: Responses = {}; |
| 190 | + |
| 191 | + // First get the response type of the method |
| 192 | + if (route.returnType) { |
| 193 | + const schemaResult = resolveTypeSchema( |
| 194 | + route.returnType.kind === ReflectionKind.promise ? route.returnType.type : route.returnType, |
| 195 | + this.schemaRegistry, |
| 196 | + ); |
| 197 | + |
| 198 | + this.errors.push(...schemaResult.errors); |
| 199 | + |
| 200 | + responses[200] = { |
| 201 | + description: '', |
| 202 | + content: { |
| 203 | + 'application/json': { |
| 204 | + schema: schemaResult.result, |
| 205 | + }, |
| 206 | + }, |
| 207 | + }; |
| 208 | + } |
| 209 | + |
| 210 | + // Annotated responses have higher priority |
| 211 | + for (const response of route.responses) { |
| 212 | + let schema: Schema | undefined; |
| 213 | + if (response.type) { |
| 214 | + const schemaResult = resolveTypeSchema(response.type, this.schemaRegistry); |
| 215 | + schema = schemaResult.result; |
| 216 | + this.errors.push(...schemaResult.errors); |
| 217 | + } |
| 218 | + |
| 219 | + if (!responses[response.statusCode]) { |
| 220 | + responses[response.statusCode] = { |
| 221 | + description: '', |
| 222 | + content: { 'application/json': schema ? { schema } : undefined }, |
| 223 | + }; |
| 224 | + } |
| 225 | + |
| 226 | + responses[response.statusCode].description ||= response.description; |
| 227 | + if (schema) { |
| 228 | + responses[response.statusCode].content['application/json']!.schema = schema; |
| 229 | + } |
| 230 | + } |
| 231 | + |
| 232 | + return responses; |
| 233 | + } |
| 234 | +} |
0 commit comments