Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(schema): Better utility for JSON parsing #21536

Merged
merged 6 commits into from
Apr 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 122 additions & 44 deletions lib/util/schema-utils.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { z } from 'zod';
import {
Json,
Json5,
looseArray,
looseRecord,
looseValue,
parseJson,
safeParseJson,
} from './schema-utils';

describe('util/schema-utils', () => {
Expand Down Expand Up @@ -99,57 +99,135 @@ describe('util/schema-utils', () => {
});
});

describe('parseJson', () => {
describe('Json', () => {
it('parses json', () => {
const res = parseJson('{"foo": "bar"}', z.object({ foo: z.string() }));
expect(res).toEqual({ foo: 'bar' });
});
const Schema = Json.pipe(z.object({ foo: z.literal('bar') }));

expect(Schema.parse('{"foo": "bar"}')).toEqual({ foo: 'bar' });

expect(Schema.safeParse(42)).toMatchObject({
error: {
issues: [
{
message: 'Expected string, received number',
code: 'invalid_type',
expected: 'string',
received: 'number',
path: [],
},
],
},
success: false,
});

it('throws on invalid json', () => {
expect(() =>
parseJson('{"foo": "bar"', z.object({ foo: z.string() }))
).toThrow(SyntaxError);
});
expect(Schema.safeParse('{"foo": "foo"}')).toMatchObject({
error: {
issues: [
{
message: 'Invalid literal value, expected "bar"',
code: 'invalid_literal',
expected: 'bar',
received: 'foo',
path: ['foo'],
},
],
},
success: false,
});

it('throws on invalid schema', () => {
expect(() =>
parseJson('{"foo": "bar"}', z.object({ foo: z.number() }))
).toThrow(z.ZodError);
});
});
expect(Schema.safeParse('["foo", "bar"]')).toMatchObject({
error: {
issues: [
{
message: 'Expected object, received array',
code: 'invalid_type',
expected: 'object',
received: 'array',
path: [],
},
],
},
success: false,
});

describe('safeParseJson', () => {
it('parses json', () => {
const res = safeParseJson(
'{"foo": "bar"}',
z.object({ foo: z.string() })
);
expect(res).toEqual({ foo: 'bar' });
expect(Schema.safeParse('{{{}}}')).toMatchObject({
error: {
issues: [
{
message: 'Invalid JSON',
code: 'custom',
path: [],
},
],
},
success: false,
});
});
});

it('returns null on invalid json', () => {
const res = safeParseJson('{"foo": "bar"', z.object({ foo: z.string() }));
expect(res).toBeNull();
});
describe('Json5', () => {
it('parses JSON5', () => {
const Schema = Json5.pipe(z.object({ foo: z.literal('bar') }));

expect(Schema.parse('{"foo": "bar"}')).toEqual({ foo: 'bar' });

expect(Schema.safeParse(42)).toMatchObject({
error: {
issues: [
{
message: 'Expected string, received number',
code: 'invalid_type',
expected: 'string',
received: 'number',
path: [],
},
],
},
success: false,
});

it('returns null on invalid schema', () => {
const res = safeParseJson(
'{"foo": "bar"}',
z.object({ foo: z.number() })
);
expect(res).toBeNull();
});
expect(Schema.safeParse('{"foo": "foo"}')).toMatchObject({
error: {
issues: [
{
message: 'Invalid literal value, expected "bar"',
code: 'invalid_literal',
expected: 'bar',
received: 'foo',
path: ['foo'],
},
],
},
success: false,
});

it('runs callback on invalid json', () => {
const callback = jest.fn();
safeParseJson('{"foo": "bar"', z.object({ foo: z.string() }), callback);
expect(callback).toHaveBeenCalledWith(expect.any(SyntaxError));
});
expect(Schema.safeParse('["foo", "bar"]')).toMatchObject({
error: {
issues: [
{
message: 'Expected object, received array',
code: 'invalid_type',
expected: 'object',
received: 'array',
path: [],
},
],
},
success: false,
});

it('runs callback on invalid schema', () => {
const callback = jest.fn();
safeParseJson('{"foo": "bar"}', z.object({ foo: z.number() }), callback);
expect(callback).toHaveBeenCalledWith(expect.any(z.ZodError));
expect(Schema.safeParse('{{{}}}')).toMatchObject({
error: {
issues: [
{
message: 'Invalid JSON5',
code: 'custom',
path: [],
},
],
},
success: false,
});
});
});
});
37 changes: 17 additions & 20 deletions lib/util/schema-utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import JSON5 from 'json5';
import type { JsonValue } from 'type-fest';
import { z } from 'zod';

export function looseArray<T extends z.ZodTypeAny>(
Expand Down Expand Up @@ -91,26 +93,21 @@ export function looseValue<T, U extends z.ZodTypeDef, V>(
return schemaWithFallback;
}

export function parseJson<
T = unknown,
Schema extends z.ZodType<T> = z.ZodType<T>
>(input: string, schema: Schema): z.infer<Schema> {
const parsed = JSON.parse(input);
return schema.parse(parsed);
}
export const Json = z.string().transform((str, ctx): JsonValue => {
try {
return JSON.parse(str);
} catch (e) {
ctx.addIssue({ code: 'custom', message: 'Invalid JSON' });
return z.NEVER;
}
});
type Json = z.infer<typeof Json>;

export function safeParseJson<
T = unknown,
Schema extends z.ZodType<T> = z.ZodType<T>
>(
input: string,
schema: Schema,
catchCallback?: (e: SyntaxError | z.ZodError) => void
): z.infer<Schema> | null {
export const Json5 = z.string().transform((str, ctx): JsonValue => {
try {
return parseJson(input, schema);
} catch (err) {
catchCallback?.(err);
return null;
return JSON5.parse(str);
} catch (e) {
ctx.addIssue({ code: 'custom', message: 'Invalid JSON5' });
return z.NEVER;
}
}
});