JacobWeisenburger / zod_utilz

Framework agnostic utilities for Zod
MIT License
158 stars 9 forks source link

Proposal flatSafeParseAsync #12

Closed sjdonado closed 4 months ago

sjdonado commented 5 months ago

I found this useful when you have to do several validations in a row

- const resultUser = await UserSchema.safeParseAsync(userData);
- if (!resultUser.success) {
- throw new Error('Error parsing user');
- }
- const user = resultUser.data;
- const resultUserSession = await UserSessionSchema.safeParseAsync(sessionData);
- if (!resultUserSession.success) {
- throw new Error('Error parsing user session');
- }
- const userSession = resultUserSession.data;
+ const user = await flatSafeParseAsync(UserSchema, userData);
+ const userSession = await flatSafeParseAsync(UserSessionSchema, sessionData);

very open to feedback :)

JacobWeisenburger commented 5 months ago

Is this what you are looking for? https://github.com/colinhacks/zod#parseasync

try {
    const schema = z.object( { name: z.string(), age: z.number() } )
    await schema.parseAsync( { name: null, age: 42 } )
} catch ( error ) {
    console.log( ( error as any ).issues )
    // [
    //     {
    //         code: "invalid_type",
    //         expected: "string",
    //         received: "null",
    //         path: [ "name" ],
    //         message: "Expected string, received null",
    //     }
    // ]
}
sjdonado commented 5 months ago

Is this what you are looking for? https://github.com/colinhacks/zod#parseasync

try {
    const schema = z.object( { name: z.string(), age: z.number() } )
    await schema.parseAsync( { name: null, age: 42 } )
} catch ( error ) {
    console.log( ( error as any ).issues )
    // [
    //     {
    //         code: "invalid_type",
    //         expected: "string",
    //         received: "null",
    //         path: [ "name" ],
    //         message: "Expected string, received null",
    //     }
    // ]
}

The error is the same, but the response is not flat, it always returns { success, data, errors }, so it's kinda misleading to have a try catch and inside a if (result.success) check.

JacobWeisenburger commented 5 months ago

In the example that I gave, I don't see { success, data, errors }, so I don't understand what you are talking about. I also don't see if (result.success). Please explain.

sjdonado commented 4 months ago

@JacobWeisenburger you right, this is not necessary. My bad, we can close it