|
| 1 | +import { Construct, IConstruct } from 'constructs'; |
| 2 | +import type { OpenAPIV3_1 } from 'openapi-types'; |
| 3 | +import { Info } from './info.js'; |
| 4 | +import { Path } from './path.js'; |
| 5 | +import { Schema } from './schema.js'; |
| 6 | +import { SecurityRequirement } from './security-requirement.js'; |
| 7 | +import { SecurityScheme } from './security-scheme.js'; |
| 8 | +import type { DocumentOptions, OpenApiVersion } from './index.js'; |
| 9 | + |
| 10 | +export class Api extends Construct { |
| 11 | + private openapi: OpenApiVersion; |
| 12 | + |
| 13 | + constructor(options: DocumentOptions) { |
| 14 | + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any |
| 15 | + super(undefined as any, ''); |
| 16 | + |
| 17 | + this.openapi = options.openapi; |
| 18 | + } |
| 19 | + |
| 20 | + public static of(c: IConstruct): Api { |
| 21 | + const { scope } = c.node; |
| 22 | + |
| 23 | + if (!scope) { |
| 24 | + // Api is the only construct without a scope. |
| 25 | + return c as Api; |
| 26 | + } |
| 27 | + |
| 28 | + return Api.of(scope); |
| 29 | + } |
| 30 | + |
| 31 | + public synth(): OpenAPIV3_1.Document { |
| 32 | + const [info] = this.node |
| 33 | + .findAll() |
| 34 | + .filter((child): child is Info => child instanceof Info); |
| 35 | + |
| 36 | + if (!info) { |
| 37 | + throw new Error('bad'); |
| 38 | + } |
| 39 | + |
| 40 | + const schemas = this.node |
| 41 | + .findAll() |
| 42 | + .filter((child): child is Schema => child instanceof Schema); |
| 43 | + |
| 44 | + return { |
| 45 | + openapi: this.openapi, |
| 46 | + info: info.synth(), |
| 47 | + components: { |
| 48 | + schemas: schemas.reduce< |
| 49 | + Required<OpenAPIV3_1.ComponentsObject>['schemas'] |
| 50 | + >((acc, schema) => { |
| 51 | + acc[schema.name] = schema.synth(); |
| 52 | + return acc; |
| 53 | + }, {}), |
| 54 | + securitySchemes: Object.fromEntries( |
| 55 | + this.node |
| 56 | + .findAll() |
| 57 | + .filter( |
| 58 | + (child): child is SecurityScheme => |
| 59 | + child instanceof SecurityScheme, |
| 60 | + ) |
| 61 | + .map((child) => [child.node.id, child.synth()]), |
| 62 | + ), |
| 63 | + }, |
| 64 | + paths: Object.fromEntries( |
| 65 | + this.node |
| 66 | + .findAll() |
| 67 | + .filter((child): child is Path => child instanceof Path) |
| 68 | + .map((child) => [child.options.path, child.synth()]), |
| 69 | + ), |
| 70 | + security: this.node.children |
| 71 | + .filter( |
| 72 | + (child): child is SecurityRequirement => |
| 73 | + child instanceof SecurityRequirement, |
| 74 | + ) |
| 75 | + .map((child) => child.synth()), |
| 76 | + }; |
| 77 | + } |
| 78 | +} |
0 commit comments