Optional formatter not work properly in NodeJS API
It seems that options.formatter is not being passed to the recursive function correctly.
Problem
Here is my code.
import openapiTS, { SwaggerToTSOptions } from 'openapi-typescript';
const schemasWork = {
Post: {
type: 'array',
description: 'Tags',
items: {
$ref: '#/components/schemas/Tag'
}
}
};
const schemasNotWork = {
Post: {
title: 'Post',
type: 'object',
properties: {
postTitle: {
type: 'string',
description: 'Title'
},
tags: {
type: 'array',
description: 'Tags',
items: {
$ref: '#/components/schemas/Tag'
}
}
}
}
};
const options: SwaggerToTSOptions = {
rawSchema: true,
version: 3,
formatter: node => {
const ref = (node as any).$ref;
if (typeof ref !== 'undefined') {
// Just extract referenced schema name (for this example, "Tag")
return (ref as string).replace(RegExp(/^.*\/(.*)$/g), (_, ...args) => args[0]);
}
}
};
const resultWork = openapiTS(schemasWork, options);
const resultNotWork = openapiTS(schemasNotWork, options);
console.log(resultWork);
console.log(resultNotWork);
and, I got
// ~ Some comments
// resultWork
export interface schemas {
/** Tags */
Post: Tag[]; // <- HERE!
}
// ~ Some comments
// resultNotWork
export interface schemas {
Post: {
/** Title */
postTitle?: string;
/** Tags */
tags?: components["schemas"]["Tag"][]; // <- HERE!
} & { [key: string]: any };
}
but, I want the result like this even for schemasNotWork
export interface schemas {
Post: {
/** Title */
postTitle?: string;
/** Tags */
tags?: Tag[]; // <- HERE!
} & { [key: string]: any };
}
Question
Is there any reason not to pass options.formatter to transformSchemaObjMap function inside transformSchemaObj function?
If I pass options.formatter to transformSchemaObjMap below, I got the result I want.
https://github.com/drwpow/openapi-typescript/blob/84fe1904d529c72188c1bd225cb9ba9e0e702da5/src/transform/schema.ts#L115-L119
I changed it like this
let properties = transformSchemaObjMap(node.properties || {}, {
immutableTypes: options.immutableTypes,
required: node.required,
version: options.version,
formatter: options.formatter
});
I support @Chrg1001 claim issued here. I have (nearly the same) problem - need to convert the score property type from string to number:
properties:
score:
title: "Percentage value of the score"
type: "string"
format: "percentage"
I have tried to do so (as documented):
const types = openapiTS(jsSchema, {
formatter(node) {
if (node.format === 'percentage') {
return "number";
}
}});
Unfortunately that does not work and it turned out that the formatter is not passed around :(.
Thanks for raising. We do have tests for the formatter; are you able to add a PR with a failing test? That should be a good starting point.