Skip to content

Commit

Permalink
Merge pull request #789 from BitGo/DX-458-parse-fields
Browse files Browse the repository at this point in the history
feat(openapi-generator): parse `examples` and `default` in apiSpec as the schema type
  • Loading branch information
bitgopatmcl authored Jun 7, 2024
2 parents 8eb75bf + ad98b73 commit 26fed46
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
23 changes: 21 additions & 2 deletions packages/openapi-generator/src/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,25 @@ function schemaToOpenAPI(
}
};

/**
* 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.
*
* @param schema A schema object
* @param fieldValue The value to parse
* @returns the parsed value
*/
const parseField = (schema: Schema, fieldValue: string): any => {
if (schema.type === 'number' || schema.type === 'integer') {
return Number(fieldValue);
} else if (schema.type === 'boolean') {
return fieldValue === 'true';
} else if (schema.type === 'null') {
return null;
} else {
return fieldValue;
}
};

function buildDefaultOpenAPIObject(schema: Schema): OpenAPIV3.SchemaObject {
const defaultValue = getTagName(schema, 'default');
const example = getTagName(schema, 'example');
Expand All @@ -157,10 +176,10 @@ function schemaToOpenAPI(
const description = schema.comment?.description;

const defaultOpenAPIObject = {
...(defaultValue ? { default: defaultValue } : {}),
...(defaultValue ? { default: parseField(schema, defaultValue) } : {}),
...(deprecated ? { deprecated: true } : {}),
...(description ? { description } : {}),
...(example ? { example } : {}),
...(example ? { example: parseField(schema, example) } : {}),
...(maxLength ? { maxLength: Number(maxLength) } : {}),
...(minLength ? { minLength: Number(minLength) } : {}),
...(pattern ? { pattern } : {}),
Expand Down
2 changes: 1 addition & 1 deletion packages/openapi-generator/test/openapi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2119,7 +2119,7 @@ testCase('route with descriptions, patterns, and examples', ROUTE_WITH_DESCRIPTI
foo: {
type: 'number',
description: 'foo description',
example: '12345',
example: 12345,
pattern: '^[1-9][0-9]{4}$'
},
child: {
Expand Down

0 comments on commit 26fed46

Please sign in to comment.