Skip to content

Commit

Permalink
map schema.nullable more cleanly
Browse files Browse the repository at this point in the history
  • Loading branch information
jloleysens committed Aug 9, 2024
1 parent 1303bfe commit 06bc1a3
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,39 @@ describe('processEnum', () => {
],
},
},
{
name: 'correctly transforms schema.nullable inputs',
input: {
anyOf: [
{
description: 'test',
type: 'object',
properties: {
test: {
type: 'string',
},
},
required: ['test'],
},
{
enum: [],
nullable: true,
type: undefined,
},
],
} as OpenAPIV3.SchemaObject,
expected: {
description: 'test',
type: 'object',
properties: {
test: {
type: 'string',
},
},
required: ['test'],
nullable: true,
},
},
])('$name', ({ input, expected }) => {
processEnum(input);
expect(input).toEqual(expected);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,38 @@
import type { OpenAPIV3 } from 'openapi-types';
import { isReferenceObject } from '../../../common';

export const processEnum = (schema: OpenAPIV3.SchemaObject) => {
if (!schema.anyOf) return;
/** Identify special case output of schema.nullable() */
const isNullableOutput = (schema: OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject) => {
return (
!isReferenceObject(schema) &&
Object.keys(schema).length === 3 &&
schema.enum?.length === 0 &&
schema.nullable === true &&
schema.type === undefined
);
};

/**
* Handle special case output of schema.nullable()
*
* We go from:
* { anyOf: [ { type: 'string' }, { nullable: true, enum: [] } ] }
*
* To:
* { type: 'string', nullable: true }
*/
const processNullableOutput = (schema: OpenAPIV3.SchemaObject) => {
if (schema.anyOf!.length !== 2) return false;
const idx = schema.anyOf!.findIndex((item) => isNullableOutput(item));
if (idx === -1) return false;
const anyOf = schema.anyOf!;
delete schema.anyOf;
schema.nullable = true;
Object.assign(schema, anyOf[1 - idx]);
return true;
};

const prettifyEnum = (schema: OpenAPIV3.SchemaObject) => {
const result: unknown[] = [];
let type: OpenAPIV3.SchemaObject['type'];
for (const item of schema.anyOf!) {
Expand All @@ -24,3 +54,9 @@ export const processEnum = (schema: OpenAPIV3.SchemaObject) => {
schema.enum = result;
delete schema.anyOf;
};

export const processEnum = (schema: OpenAPIV3.SchemaObject) => {
if (!schema.anyOf) return;
if (processNullableOutput(schema)) return;
prettifyEnum(schema);
};

0 comments on commit 06bc1a3

Please sign in to comment.