Skip to content

Commit

Permalink
feat(formats): jsonSchemaLoose format should search for enum keyword (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
P0lip authored Nov 7, 2023
1 parent 2fdc5a4 commit 0835545
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
9 changes: 9 additions & 0 deletions packages/formats/src/__tests__/jsonSchema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,15 @@ describe('JSON Schema format', () => {
expect(jsonSchemaLoose({ not: {} }, null)).toBe(true);
});

it('recognizes by the presence of valid "enum"', () => {
expect(jsonSchemaLoose({ enum: ['1'] }, null)).toBe(true);
expect(jsonSchemaLoose({ enum: [] }, null)).toBe(true);

expect(jsonSchemaLoose({ enum: 2 }, null)).toBe(false);
expect(jsonSchemaLoose({ enum: {} }, null)).toBe(false);
expect(jsonSchemaLoose({ enum: null }, null)).toBe(false);
});

describe('mixed', () => {
it('invalid type but valid combiner', () => {
expect(jsonSchemaLoose({ type: 'foo', allOf: [] }, null)).toBe(true);
Expand Down
7 changes: 6 additions & 1 deletion packages/formats/src/jsonSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ const hasValidJSONSchemaType = (document: Partial<{ type?: unknown }>): boolean
return Array.isArray(document.type) && document.type.every(type => KNOWN_JSON_SCHEMA_TYPES.includes(type));
};

const hasValidJSONSchemaEnumKeyword = (document: Record<string, unknown>): boolean => Array.isArray(document['enum']);

const hasValidJSONSchemaCompoundKeyword = (document: Record<string, unknown>): boolean =>
KNOWN_JSON_SCHEMA_COMPOUND_KEYWORDS.some(
combiner => combiner in document && typeof document[combiner] === 'object' && document[combiner] !== null,
Expand All @@ -43,7 +45,10 @@ export const jsonSchemaLoose: Format<Record<string, unknown>> = (
document: unknown,
): document is Record<string, unknown> =>
isPlainObject(document) &&
(isJsonSchema(document) || hasValidJSONSchemaType(document) || hasValidJSONSchemaCompoundKeyword(document));
(isJsonSchema(document) ||
hasValidJSONSchemaType(document) ||
hasValidJSONSchemaEnumKeyword(document) ||
hasValidJSONSchemaCompoundKeyword(document));

jsonSchemaLoose.displayName = 'JSON Schema (loose)';

Expand Down

0 comments on commit 0835545

Please sign in to comment.