Skip to content

Commit c647cb6

Browse files
committed
feat(openapi-generator): parse examples and default in apiSpec as the schema type
DX-458
1 parent 8eb75bf commit c647cb6

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

packages/openapi-generator/src/openapi.ts

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,30 @@ function schemaToOpenAPI(
133133
}
134134
};
135135

136+
/**
137+
* This function will return the field value parsed as the type of the schema. i.e. if the schema is a number, it will return the field as a JS number.
138+
*
139+
* @param schema A schema object
140+
* @param field The target field to parse in that schema
141+
* @returns the parsed value
142+
*/
143+
const parseField = (schema: Schema, field: string): any => {
144+
const fieldValue = getTagName(schema, field);
145+
if (!fieldValue) {
146+
return;
147+
}
148+
149+
if (schema.type === 'number' || schema.type === 'integer') {
150+
return Number(fieldValue);
151+
} else if (schema.type === 'boolean') {
152+
return fieldValue === 'true';
153+
} else if (schema.type === 'null') {
154+
return null;
155+
} else {
156+
return fieldValue;
157+
}
158+
};
159+
136160
function buildDefaultOpenAPIObject(schema: Schema): OpenAPIV3.SchemaObject {
137161
const defaultValue = getTagName(schema, 'default');
138162
const example = getTagName(schema, 'example');
@@ -157,10 +181,10 @@ function schemaToOpenAPI(
157181
const description = schema.comment?.description;
158182

159183
const defaultOpenAPIObject = {
160-
...(defaultValue ? { default: defaultValue } : {}),
184+
...(defaultValue ? { default: parseField(schema, 'default') } : {}),
161185
...(deprecated ? { deprecated: true } : {}),
162186
...(description ? { description } : {}),
163-
...(example ? { example } : {}),
187+
...(example ? { example: parseField(schema, 'example') } : {}),
164188
...(maxLength ? { maxLength: Number(maxLength) } : {}),
165189
...(minLength ? { minLength: Number(minLength) } : {}),
166190
...(pattern ? { pattern } : {}),

packages/openapi-generator/test/openapi.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2119,7 +2119,7 @@ testCase('route with descriptions, patterns, and examples', ROUTE_WITH_DESCRIPTI
21192119
foo: {
21202120
type: 'number',
21212121
description: 'foo description',
2122-
example: '12345',
2122+
example: 12345,
21232123
pattern: '^[1-9][0-9]{4}$'
21242124
},
21252125
child: {

0 commit comments

Comments
 (0)