Skip to content

Commit

Permalink
feat: add safe parsing support
Browse files Browse the repository at this point in the history
  • Loading branch information
StyleShit committed Jul 13, 2024
1 parent aa77f4a commit 907b9c1
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/curvy-laws-provide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'bodek': patch
---

Add safe parsing support
21 changes: 21 additions & 0 deletions src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,4 +148,25 @@ describe('Bodek', () => {
expect(() => schema.parse(-2)).toThrow('Number must be positive');
expect(() => schema.parse(3)).toThrow('Number must be even');
});

it('should support safe parsing', () => {
// Arrange.
const schema = b.number();

// Assert - valid.
expect(schema.safeParse(123)).toEqual({
success: true,
data: 123,
});

// Assert - invalid.
expect(schema.safeParse('hello')).toEqual({
success: false,
error: new Error('hello is not a number'),
});

expectTypeOf(schema.safeParse(123)).toEqualTypeOf<
{ success: true; data: number } | { success: false; error: Error }
>();
});
});
20 changes: 20 additions & 0 deletions src/schemas/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ type RefineParams = {
message?: string;
};

type SafeParseResult<T> =
| { success: true; data: T }
| { success: false; error: Error };

export abstract class Schema<Type> {
private refinements: Array<{
validator: RefineValidator<Type>;
Expand All @@ -26,6 +30,22 @@ export abstract class Schema<Type> {
return parsed;
}

safeParse(value: unknown, message?: string): SafeParseResult<Type> {
try {
const data = this.parse(value, message);

return {
success: true,
data,
};
} catch (error) {
return {
success: false,
error: error as Error,
};
}
}

refine(validator: RefineValidator<Type>, params?: RefineParams) {
this.refinements.push({
validator,
Expand Down

0 comments on commit 907b9c1

Please sign in to comment.