feat: Schema utility for URL parsing (#23043)

This commit is contained in:
Sergei Zharinov 2023-06-29 19:22:26 +03:00 committed by GitHub
parent 674f9cbfcc
commit fd3d577a8a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 1 deletions

View file

@ -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', () => {
@ -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');
});
});
});

View file

@ -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;
}
});