Skip to content

Commit 26fed46

Browse files
authored
Merge pull request #789 from BitGo/DX-458-parse-fields
feat(openapi-generator): parse `examples` and `default` in apiSpec as the schema type
2 parents 8eb75bf + ad98b73 commit 26fed46

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

packages/openapi-generator/src/openapi.ts

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,25 @@ 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 fieldValue The value to parse
141+
* @returns the parsed value
142+
*/
143+
const parseField = (schema: Schema, fieldValue: string): any => {
144+
if (schema.type === 'number' || schema.type === 'integer') {
145+
return Number(fieldValue);
146+
} else if (schema.type === 'boolean') {
147+
return fieldValue === 'true';
148+
} else if (schema.type === 'null') {
149+
return null;
150+
} else {
151+
return fieldValue;
152+
}
153+
};
154+
136155
function buildDefaultOpenAPIObject(schema: Schema): OpenAPIV3.SchemaObject {
137156
const defaultValue = getTagName(schema, 'default');
138157
const example = getTagName(schema, 'example');
@@ -157,10 +176,10 @@ function schemaToOpenAPI(
157176
const description = schema.comment?.description;
158177

159178
const defaultOpenAPIObject = {
160-
...(defaultValue ? { default: defaultValue } : {}),
179+
...(defaultValue ? { default: parseField(schema, defaultValue) } : {}),
161180
...(deprecated ? { deprecated: true } : {}),
162181
...(description ? { description } : {}),
163-
...(example ? { example } : {}),
182+
...(example ? { example: parseField(schema, example) } : {}),
164183
...(maxLength ? { maxLength: Number(maxLength) } : {}),
165184
...(minLength ? { minLength: Number(minLength) } : {}),
166185
...(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)