UNPKG

openapi-ts-json-schema

Version:

OpenAPI to JSON schema generator with TypeScript in mind

59 lines (58 loc) 2.63 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const OUTPUT_FILE_NAME = 'fastify-integration.ts'; const OPEN_API_COMPONENTS_SCHEMAS_PATH = '/components/schemas/'; const defaultSchemaFilter = ({ id }) => { return id.startsWith(OPEN_API_COMPONENTS_SCHEMAS_PATH); }; const fastifyIntegrationPlugin = ({ schemaFilter = defaultSchemaFilter, } = {}) => ({ onInit: async ({ options }) => { // Force "keep" refHandling options.refHandling = 'keep'; options.$idMapper = ({ id }) => id; }, onBeforeGeneration: async ({ outputPath, metaData, options, utils }) => { // Derive the schema data necessary to generate the declarations const allSchemas = [...metaData.schemas] .map(([id, schema]) => schema) .map(({ absoluteImportPath, uniqueName, id, isRef }) => { return { importPath: utils.makeRelativeModulePath({ fromDirectory: outputPath, to: absoluteImportPath, }), uniqueName, id, isRef, }; }); // @TODO: Shall we include refs of the filtered schemas? const exportedSchemas = allSchemas.filter(({ id, isRef }) => schemaFilter({ id, isRef })); let output = '// File autogenerated by "openapi-ts-json-schema". Do not edit :)'; // Generate JSON schemas import statements exportedSchemas.forEach((schema) => { output += `\n import { with$id as ${schema.uniqueName} } from "${schema.importPath}";`; }); // RefSchemas type: generate TS tuple TS type containing the types of all $ref JSON schema output += `\n\n // RefSchemas type: tuple of $ref schema types to enable json-schema-to-ts hydrate $refs via "references" option export type RefSchemas = [ ${exportedSchemas .map((schema) => `typeof ${schema.uniqueName}`) .join(',')} ];`; // schemas: generate an array of all exported JSON schema to be registered with `fastify.addSchema` output += `\n\n // schemas: array of JSON schemas to be registered with "fastify.addSchema" export const schemas = [ ${exportedSchemas.map((schema) => `${schema.uniqueName}`).join(',')} ];`; // Format and save file const formattedOutput = await utils.formatTypeScript(output); await utils.saveFile({ path: [outputPath, OUTPUT_FILE_NAME], data: formattedOutput, }); }, }); exports.default = fastifyIntegrationPlugin;