Skip to content

Commit

Permalink
feat: Schema utility for URL parsing (#23043)
Browse files Browse the repository at this point in the history
  • Loading branch information
zharinov authored Jun 29, 2023
1 parent 674f9cb commit fd3d577
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
27 changes: 26 additions & 1 deletion lib/util/schema-utils.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { z } from 'zod';
import { Json, Json5, LooseArray, LooseRecord, UtcDate } from './schema-utils';
import {
Json,
Json5,
LooseArray,
LooseRecord,
Url,
UtcDate,
} from './schema-utils';

describe('util/schema-utils', () => {
describe('LooseArray', () => {
Expand Down Expand Up @@ -270,4 +277,22 @@ describe('util/schema-utils', () => {
expect(() => UtcDate.parse('foobar')).toThrow();
});
});

describe('Url', () => {
it('parses valid URLs', () => {
const urlStr = 'https://www.example.com/foo/bar?baz=qux';
const parsedUrl = Url.parse(urlStr);
expect(parsedUrl).toMatchObject({
protocol: 'https:',
hostname: 'www.example.com',
pathname: '/foo/bar',
search: '?baz=qux',
});
});

it('throws an error for invalid URLs', () => {
const urlStr = 'invalid-url-string';
expect(() => Url.parse(urlStr)).toThrow('Invalid URL');
});
});
});
9 changes: 9 additions & 0 deletions lib/util/schema-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,3 +223,12 @@ export const UtcDate = z
}
return date;
});

export const Url = z.string().transform((str, ctx): URL => {
try {
return new URL(str);
} catch (e) {
ctx.addIssue({ code: 'custom', message: 'Invalid URL' });
return z.NEVER;
}
});

0 comments on commit fd3d577

Please sign in to comment.