@walecloud/fastify-openapi-typescript-generator
Version:
Contains utilities to generate fastify types from openapi definition for the fastify framework.
24 lines (23 loc) • 1.03 kB
JavaScript
import openapiTS, { astToString } from 'openapi-typescript';
import { disableLinter } from '../utils/consts.js';
const schemaStartPath = '#/components/schemas/';
export const generateOpenapiTypes = async (openapiFilePath, options) => {
const localPath = new URL(openapiFilePath, import.meta.url);
const { externalTypesImportFrom } = options ?? {};
const openAPITSOptions = {
inject: disableLinter,
};
if (externalTypesImportFrom) {
const externalTypesImport = 'openapiTypes';
openAPITSOptions.transform = (_, options) => {
if (options.path?.startsWith(schemaStartPath)) {
const typeName = options.path.replace(schemaStartPath, '');
return `${externalTypesImport}.${typeName}`;
}
return undefined;
};
openAPITSOptions.inject += `\nimport * as ${externalTypesImport} from "${externalTypesImportFrom}";\n`;
}
const ast = await openapiTS(localPath, openAPITSOptions);
return astToString(ast);
};