Skip to content

Commit b1cf915

Browse files
committed
feat: add $UrlLike
1 parent 2fa456f commit b1cf915

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/__tests__/zod.test.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import * as module from 'node:module';
33
import { describe, expect, it } from 'vitest';
44
import { z } from 'zod';
55

6-
import { $BooleanLike, $NumberLike, isZodType } from '../zod.js';
6+
import { $BooleanLike, $NumberLike, $UrlLike, isZodType } from '../zod.js';
77

88
const require = module.createRequire(import.meta.url);
99

@@ -71,3 +71,16 @@ describe('$NumberLike', () => {
7171
expect($IntLike.safeParse('1').data).toBe(1);
7272
});
7373
});
74+
75+
describe('$UrlLike', () => {
76+
it('should parse a url', () => {
77+
const result = $UrlLike.safeParse(new URL('https://opendatacapture.org'));
78+
expect(result.success).toBe(true);
79+
expect(result.data).toBeInstanceOf(URL);
80+
});
81+
it('should parse a url string', () => {
82+
const result = $UrlLike.safeParse('https://opendatacapture.org');
83+
expect(result.success).toBe(true);
84+
expect(result.data).toBeInstanceOf(URL);
85+
});
86+
});

src/zod.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,16 @@ export const $NumberLike: z.ZodType<number, z.ZodTypeDef, any> = z.preprocess((a
2929
}
3030
return arg;
3131
}, z.number());
32+
33+
export const $UrlLike: z.ZodType<URL, z.ZodTypeDef, any> = z.preprocess(
34+
(arg) => {
35+
if (arg instanceof URL) {
36+
return arg.href;
37+
}
38+
return arg;
39+
},
40+
z
41+
.string()
42+
.url()
43+
.transform((arg) => new URL(arg))
44+
);

0 commit comments

Comments
 (0)