UNPKG

openapi-ts-json-schema

Version:

Generate TypeScript-first JSON schemas from OpenAPI definitions

62 lines (61 loc) 2.85 kB
import generateSchemaWith$idPlugin from './generateSchemaWith$idPlugin.js'; 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; // Register Generate schema with $id plugin options.plugins.push(generateSchemaWith$idPlugin()); }, onBeforeGeneration: async ({ outputPath, metaData, options, utils }) => { // Derive the schema data necessary to generate the declarations const allSchemas = [...metaData.schemas] .map(([_id, schema]) => schema) .filter((schema) => schema.shouldBeGenerated) .map(({ absoluteImportPath, uniqueName, id, isRef }) => { return { importPath: utils.makeRelativeImportPath({ fromDirectory: outputPath, toModule: absoluteImportPath, moduleSystem: options.moduleSystem, }), 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, }); }, }); export default fastifyIntegrationPlugin;