Skip to content

Commit 43fa25b

Browse files
JamieB-gujamesmockettmarjisound
authored
Added fromValibot to Result (#15363)
Allows us to convert Valibot's result into our internal `Result` type, for ease of use with other code. Co-authored-by: James M <1166188+jamesmockett@users.noreply.github.com> Co-authored-by: Marjan K <15894063+marjisound@users.noreply.github.com>
1 parent 9b766af commit 43fa25b

2 files changed

Lines changed: 45 additions & 1 deletion

File tree

dotcom-rendering/src/lib/result.test.ts

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { error, ok, type Result } from './result';
1+
import { literal, safeParse } from 'valibot';
2+
import { error, fromValibot, ok, type Result } from './result';
23

34
describe('ok', () => {
45
it('creates an instance of Ok', () => {
@@ -160,3 +161,26 @@ describe('getErrorOrThrow', () => {
160161
);
161162
});
162163
});
164+
165+
describe('fromValibot', () => {
166+
const schema = literal('string literal');
167+
168+
it('creates an Ok from a successful parse result', () => {
169+
const valibotResult = safeParse(schema, 'string literal');
170+
171+
const result = fromValibot(valibotResult);
172+
const value = result.getOrThrow('Expected an Ok');
173+
174+
expect(value).toBe('string literal');
175+
});
176+
177+
it('creates an Err from an unsuccessful parse result', () => {
178+
const valibotResult = safeParse(schema, 'invalid literal');
179+
180+
const result = fromValibot(valibotResult);
181+
const err = result.getErrorOrThrow('Expected an Err');
182+
183+
expect(err[0].reason).toBe('type');
184+
expect(err[0].context).toBe('literal');
185+
});
186+
});

dotcom-rendering/src/lib/result.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
1+
import type {
2+
BaseSchema,
3+
BaseSchemaAsync,
4+
Output,
5+
SafeParseResult,
6+
SchemaIssues,
7+
} from 'valibot';
8+
19
/**
210
* Represents a value or an error; it's either a {@linkcode Ok} or an
311
* {@linkcode Err}. Can be constructed with {@linkcode ok} or {@linkcode error}.
@@ -168,4 +176,16 @@ const ok = <E, A>(value: A): Result<E, A> => new Ok(value);
168176
*/
169177
const error = <E, A>(err: E): Result<E, A> => new Err(err);
170178

179+
/**
180+
* Constructs an instance of a {@linkcode Result} from a Valibot
181+
* {@linkcode SafeParseResult}, i.e. the output from Valibot `safeParse`.
182+
* @example
183+
* const valibotResult = safeParse(schema, input);
184+
* const result = fromValibot(valibotResult);
185+
*/
186+
export const fromValibot = <Schema extends BaseSchema | BaseSchemaAsync>(
187+
result: SafeParseResult<Schema>,
188+
): Result<SchemaIssues, Output<Schema>> =>
189+
result.success ? ok(result.output) : error(result.issues);
190+
171191
export { Result, ok, error };

0 commit comments

Comments
 (0)