Skip to content

Commit 6510312

Browse files
committed
feat: add safeParse
1 parent 84fd18b commit 6510312

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

src/__tests__/zod.test.ts

Lines changed: 25 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, $Uint8ArrayLike, $UrlLike, isZodType } from '../zod.js';
6+
import { $BooleanLike, $NumberLike, $Uint8ArrayLike, $UrlLike, isZodType, safeParse } from '../zod.js';
77

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

@@ -116,3 +116,27 @@ describe('$Uint8ArrayLike', () => {
116116
expect([...result.data!]).toEqual([7, 8, 9]);
117117
});
118118
});
119+
120+
describe('safeParse', () => {
121+
const $Schema = z.object({ foo: z.enum(['1', '2']).transform(Number) });
122+
it('should return an Ok result with the parsed data if successful', () => {
123+
const result = safeParse({ foo: '1' }, $Schema);
124+
expect(result.isOk() && result.value).toStrictEqual({ foo: 1 });
125+
});
126+
it('should return an Err result with the data and validation issues if unsuccessful', () => {
127+
const result = safeParse({ foo: '0' }, $Schema);
128+
expect(result.isErr() && result.error).toMatchObject({
129+
details: {
130+
data: {
131+
foo: '0'
132+
},
133+
issues: [
134+
expect.objectContaining({
135+
code: z.ZodIssueCode.invalid_enum_value,
136+
path: ['foo']
137+
})
138+
]
139+
}
140+
});
141+
});
142+
});

src/zod.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1+
import { ok } from 'neverthrow';
2+
import type { Result } from 'neverthrow';
13
import { z } from 'zod';
24

5+
import { ValidationException } from './exception.js';
36
import { isNumberLike, parseNumber } from './number.js';
47
import { isObject } from './object.js';
58

@@ -51,3 +54,19 @@ export const $Uint8ArrayLike: z.ZodType<Uint8Array, z.ZodTypeDef, any> = z
5154
}
5255
return arg;
5356
});
57+
58+
export function safeParse<TSchema extends z.ZodTypeAny>(
59+
data: unknown,
60+
$Schema: TSchema
61+
): Result<z.infer<TSchema>, typeof ValidationException.Instance> {
62+
const result = $Schema.safeParse(data);
63+
if (!result.success) {
64+
return ValidationException.asErr({
65+
details: {
66+
data,
67+
issues: result.error.issues
68+
}
69+
});
70+
}
71+
return ok(result.data);
72+
}

0 commit comments

Comments
 (0)