Skip to content

Commit

Permalink
fix(functions): schema should respect "auto" dialect (#1771)
Browse files Browse the repository at this point in the history
  • Loading branch information
P0lip committed Aug 16, 2021
1 parent d2fec61 commit ed1621c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
17 changes: 15 additions & 2 deletions packages/functions/src/__tests__/schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,15 @@ describe('Core Functions / Schema', () => {
exclusiveMaximum: true,
};

expect(await runSchema(2, { schema })).toEqual([
const result = await runSchema(2, { schema });
expect(result).toStrictEqual([
{
message: 'Number must be < 2',
path: [],
},
]);

expect(await runSchema(2, { schema, dialect: 'auto' })).toStrictEqual(result);
});

it('validates draft 6', async () => {
Expand All @@ -28,12 +31,15 @@ describe('Core Functions / Schema', () => {
type: 'string',
};

expect(await runSchema(2, { schema })).toEqual([
const result = await runSchema(2, { schema });
expect(result).toEqual([
{
message: 'Value type must be string',
path: [],
},
]);

expect(await runSchema(2, { schema, dialect: 'auto' })).toStrictEqual(result);
});

describe('validates falsy values such as', () => {
Expand Down Expand Up @@ -389,6 +395,13 @@ describe('Core Functions / Schema', () => {
{ schema: { type: 'string' }, dialect: 'auto' },
{ schema: { type: 'string' }, allErrors: true },
{ schema: { type: 'string' }, dialect: 'draft2019-09', allErrors: false },
{
schema: { type: 'string' },
dialect: 'draft2019-09',
prepareResults() {
/* no-op */
},
},
])('given valid %p options, should not throw', async opts => {
expect(await runSchema('', opts)).toBeInstanceOf(Array);
});
Expand Down
8 changes: 6 additions & 2 deletions packages/functions/src/schema/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,13 @@ export default createRulesetFunction<unknown, Options>(
},
dialect: {
enum: ['auto', 'draft4', 'draft6', 'draft7', 'draft2019-09', 'draft2020-12'],
default: 'auto',
},
allErrors: {
type: 'boolean',
default: false,
},
prepareResults: {},
prepareResults: true,
},
required: ['schema'],
type: 'object',
Expand All @@ -56,7 +58,9 @@ export default createRulesetFunction<unknown, Options>(

try {
let validator;
const dialect = opts?.dialect ?? detectDialect(schemaObj) ?? 'draft7';
const dialect =
(opts.dialect === void 0 || opts.dialect === 'auto' ? detectDialect(schemaObj) : opts?.dialect) ?? 'draft7';

if (dialect === 'draft4' || dialect === 'draft6') {
schemaObj = JSON.parse(JSON.stringify(schemaObj)) as Record<string, unknown>;
schemaObj.$schema = 'http://json-schema.org/draft-07/schema#';
Expand Down

0 comments on commit ed1621c

Please sign in to comment.