Skip to content

Instantly share code, notes, and snippets.

@up1
Last active February 2, 2025 08:22
Show Gist options
  • Save up1/10184bd7ef7a4b80dd439a0864c11d2c to your computer and use it in GitHub Desktop.
Save up1/10184bd7ef7a4b80dd439a0864c11d2c to your computer and use it in GitHub Desktop.
Demo Standard Schema
$vitest
RERUN src/validate/MyValidator.test.tsx x2
✓ src/validate/MyValidator.test.tsx (3 tests) 3ms
✓ standardValidate with Zod
✓ standardValidate with ValiBot
✓ standardValidate with ArkType
Test Files 1 passed (1)
Tests 3 passed (3)
Start at 11:20:11
Duration 92ms
PASS Waiting for file changes...
press h to show help, press q to quit
// Test case
import { standardValidate } from './MyValidator';
import * as z from 'zod';
import * as v from 'valibot';
import {type} from 'arktype';
test('standardValidate with Zod', async () => {
const schema = z.object({
name: z.string(),
age: z.number(),
});
const input = { name: 'Somkiat', age: 30 };
const output = await standardValidate(schema, input);
expect(output).toEqual(input);
});
test('standardValidate with ValiBot', async () => {
const schema = v.object({
name: v.string(),
age: v.number(),
});
const input = { name: 'Somkiat', age: 30 };
const output = await standardValidate(schema, input);
expect(output).toEqual(input);
});
test('standardValidate with ArkType', async () => {
const schema = type({
name: 'string',
age: 'number',
});
const input = { name: 'Somkiat', age: 30 };
const output = await standardValidate(schema, input);
expect(output).toEqual(input);
});
import type {StandardSchemaV1} from '@standard-schema/spec';
export async function standardValidate<T extends StandardSchemaV1>(
schema: T,
input: StandardSchemaV1.InferInput<T>
): Promise<StandardSchemaV1.InferOutput<T>> {
let result = schema['~standard'].validate(input);
if (result instanceof Promise) result = await result;
// if the `issues` field exists, the validation failed
if (result.issues) {
throw new Error(JSON.stringify(result.issues, null, 2));
}
return result.value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment