Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Schema validation #260

Open
karesztrk opened this issue Mar 21, 2025 · 0 comments
Open

Schema validation #260

karesztrk opened this issue Mar 21, 2025 · 0 comments

Comments

@karesztrk
Copy link

I'm a big fan of wretch but recently I wanted to add Schema validation to my API responses.
If I'm not mistaken wretch doesn't support it out-of-the-box (comparing to up-fetch).
I've created a tiny addon that is using validbot. Let me know what do you think.

Addon

import { type BaseIssue, type BaseSchema, type InferOutput, safeParse } from 'valibot';
import type { WretchAddon, WretchResponseChain } from 'wretch/types';

export interface ParseAddonType {
    parse: <T, C extends ParseAddonType, R, S extends BaseSchema<unknown, unknown, BaseIssue<unknown>>>(
        this: C & WretchResponseChain<T, C, R>,
        schema: S,
    ) => Promise<Awaited<InferOutput<S>>>;
}

/**
 * Parse the json response with the given schema.
 * The `parse` resolver will implicitly call the `json` resolver before the validation.
 */
const ParseAddon: WretchAddon<unknown, ParseAddonType> = {
    resolver: {
        parse(schema) {
            return this.json((data) => {
                // safe parsing here but you can use simple `parse` as well to throw ValiError 
                const { success, output, issues } = safeParse(schema, data);
                if (success) {
                    return output;
                }

                // ... throw your error
            });
        },
    },
};

export default ParseAddon;

Usage

const DataSchema = object({
   // ...
});
wretch("...").url("...").addon(ParseAddon).get().parse(DataSchema),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant