Skip to content

Commit fd3d577

Browse files
authored
feat: Schema utility for URL parsing (#23043)
1 parent 674f9cb commit fd3d577

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

lib/util/schema-utils.spec.ts

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
import { z } from 'zod';
2-
import { Json, Json5, LooseArray, LooseRecord, UtcDate } from './schema-utils';
2+
import {
3+
Json,
4+
Json5,
5+
LooseArray,
6+
LooseRecord,
7+
Url,
8+
UtcDate,
9+
} from './schema-utils';
310

411
describe('util/schema-utils', () => {
512
describe('LooseArray', () => {
@@ -270,4 +277,22 @@ describe('util/schema-utils', () => {
270277
expect(() => UtcDate.parse('foobar')).toThrow();
271278
});
272279
});
280+
281+
describe('Url', () => {
282+
it('parses valid URLs', () => {
283+
const urlStr = 'https://www.example.com/foo/bar?baz=qux';
284+
const parsedUrl = Url.parse(urlStr);
285+
expect(parsedUrl).toMatchObject({
286+
protocol: 'https:',
287+
hostname: 'www.example.com',
288+
pathname: '/foo/bar',
289+
search: '?baz=qux',
290+
});
291+
});
292+
293+
it('throws an error for invalid URLs', () => {
294+
const urlStr = 'invalid-url-string';
295+
expect(() => Url.parse(urlStr)).toThrow('Invalid URL');
296+
});
297+
});
273298
});

lib/util/schema-utils.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,3 +223,12 @@ export const UtcDate = z
223223
}
224224
return date;
225225
});
226+
227+
export const Url = z.string().transform((str, ctx): URL => {
228+
try {
229+
return new URL(str);
230+
} catch (e) {
231+
ctx.addIssue({ code: 'custom', message: 'Invalid URL' });
232+
return z.NEVER;
233+
}
234+
});

0 commit comments

Comments
 (0)