Skip to content

Latest commit

 

History

History
240 lines (173 loc) · 7.14 KB

README.md

File metadata and controls

240 lines (173 loc) · 7.14 KB

Zodkit

Zodkit is a collection of Zod utilities for SvelteKit actions, load functions, hooks and endpoints. It abstracts the complexity of parsing and validating FormData, URLSearchParams and RouteParams so they stay clean and are strongly typed. It is heavily based on Zodix by Riley Tomasek

Table of Contents

Installing

Using npm:

$ npm install zodkit zod

Using yarn:

$ yarn add zodkit zod

Using pnpm:

$ pnpm add zodkit zod

Usage

You can either import the zk object that contains all of the functions

import { zk } from 'zodkit';

or import the functions seperately

import {
    parseSearchParams,
    parseSearchParamsSafe,
    parseFormData,
    parseFormDataSafe,
    parseRouteParams,
    parseRouteParamsSafe,
} from 'zodkit';

Functions

parseSearchParams

parseSearchParams(data: URLSearchParams | RequestEvent, schema: Schema)

Parses and validates URLSearchParams. If the parsing/validation fails a 400 error will be thrown with the errors from zod, otherwise the parsed data from the schema will be returned.

import type { RequestHandler } from './$types.js';
import { zk } from 'zodkit';
import { z } from 'zod';

export const GET = ((event) => {
    const { myNumber } = zk.parseSearchParams(event, { myNumber: z.number({ coerce: true }) });
    return new Response(String(myNumber));
}) satisfies RequestHandler;

parseSearchParamsSafe

parseSearchParamsSafe(data: URLSearchParams | RequestEvent, schema: Schema)

Parses and validates URLSearchParams using .safeParse. If the parsing/validation fails a SafeParseFailure object will be returned, otherwise an object in the shape { success: true; data: T; } will be returned

import { fail } from '@sveltejs/kit';
import type { RequestHandler } from './$types.js';
import { zk } from 'zodkit';
import { z } from 'zod';

export const GET = ((event) => {
    const result = zk.parseSearchParamsSafe(event, { myNumber: z.number({ coerce: true }) });

    if (!result.success) {
        return fail(400, {
            errors: result.error.flatten().fieldErrors,
        });
    }

    return new Response(String(result.data.myNumber));
}) satisfies RequestHandler;

parseFormData

parseFormData(data: FormData | RequestEvent, schema: Schema)

Parses and validates FormData. If the parsing/validation fails a 400 error will be thrown with the errors from zod, otherwise the parsed data from the schema will be returned.

import type { RequestHandler } from './$types.js';
import { zk } from 'zodkit';
import { z } from 'zod';

export const POST = (async (event) => {
    const { myNumber } = await zk.parseFormData(event, { myNumber: z.number({ coerce: true }) });
    return new Response(String(myNumber));
}) satisfies RequestHandler;

parseFormDataSafe

async parseFormDataSafe(data: FormData | RequestEvent, schema: Schema)

Parses and validates FormData using .safeParse. If the parsing/validation fails a SafeParseFailure object will be returned, otherwise an object in the shape { success: true; data: T; } will be returned

import { fail } from '@sveltejs/kit';
import type { RequestHandler } from './$types.js';
import { zk } from 'zodkit';
import { z } from 'zod';

export const POST = (async (event) => {
    const result = await zk.parseFormDataSafe(event, { myNumber: z.number({ coerce: true }) });

    if (!result.success) {
        return fail(400, {
            errors: result.error.flatten().fieldErrors,
        });
    }

    return new Response(String(result.data.myNumber));
}) satisfies RequestHandler;

parseRouteParams

parseRouteParams(data: RouteParams | RequestEvent, schema: Schema)

Parses and validates RouteParams from event.params. If the parsing/validation fails a 400 error will be thrown with the errors from zod, otherwise the parsed data from the schema will be returned.

import type { RequestHandler } from './$types.js';
import { zk } from 'zodkit';
import { z } from 'zod';

export const GET = ((event) => {
    const { myNumber } = zk.parseRouteParams(event, { myNumber: z.number({ coerce: true }) });
    return new Response(String(myNumber));
}) satisfies RequestHandler;

parseRouteParamsSafe

parseRouteParamsSafe(data: RouteParams | RequestEvent, schema: Schema)

Parses and validates RouteParams from event.params using .safeParse. If the parsing/validation fails a SafeParseFailure object will be returned, otherwise an object in the shape { success: true; data: T; } will be returned

import { fail } from '@sveltejs/kit';
import type { RequestHandler } from './$types.js';
import { zk } from 'zodkit';
import { z } from 'zod';

export const GET = ((event) => {
    const result = zk.parseRouteParamsSafe(event, { myNumber: z.number({ coerce: true }) });

    if (!result.success) {
        return fail(400, {
            errors: result.error.flatten().fieldErrors,
        });
    }

    return new Response(String(result.data.myNumber));
}) satisfies RequestHandler;

Types

Schema

Schema is equal to ZodTypeAny | ZodRawShape; which allows us to pass in both a Zod schema:

const schema: Schema = z.object({ a: z.number(), b: z.string() });

and regular objects

const schema: Schema = { a: z.number(), b: z.string() };

RouteParams

RouteParams is equal to Partial<Record<string, string>>. It is the same format that RequestEvent.params is.

SafeParseFailure

SafeParseFailure has the shape

{
    success: false;
    errors: { [key: string] : string[] };
    response: ActionFailure<{ errors: [key: string] : string[] }>;
}

The response property can be used to return errors from a form action.

import { z } from 'zod';
import { zk } from 'zodkit';
import type { Actions } from './$types';

export const actions = {
    default: async (event) => {
        const result = await zk.parseFormDataSafe(event, {
            name: z.string().min(5);
        });

        if (!result.success) {
            return result.response
        }
    }
} satisfies Actions;