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

validation #21

Closed
Michael-Liendo opened this issue Jul 23, 2024 · 1 comment · Fixed by #22
Closed

validation #21

Michael-Liendo opened this issue Jul 23, 2024 · 1 comment · Fixed by #22
Assignees

Comments

@Michael-Liendo
Copy link
Owner

you can use Zod schema for example

this is a user schema

const schema = z.object({
    firstName: z.string(),
    lastName: z.string().optional(),
    email: z.string().email().describe("unique"),
    username: z.string().min(3).max(20).describe("unique"),
    password: z.string()
})

you can use preHandler on fastify to validate your schema like this

const requestValidation = (schema: ZodObject<any>) => {

    return async (req: FastifyRequest, reply: FastifyReply) => {

        if (!schema) return;

        const result = schema.safeParse(req.body);

        if (!req.body) {
            return reply.status(400).send({
                success: false,
                message: 'Validation error',
                errors: [
                    {
                        code: 'MISSING_BODY',
                        path: 'root',
                        message: 'Request body is missing'
                    }
                ]
            })
        }

        if (!result.success) {
            const errors = result.error.issues.map(issue => ({
                code: issue.code,
                path: issue.path.length > 0 ? issue.path.join('.') : 'root',
                message: issue.message
            }))
            reply.status(400).send({
                success: false,
                message: 'Validation error',
                errors
            })
        } else {
            return
        }
    }

}

fastify.route({
    method: "POST,
    url: "/users/create",
    preHandler: requestValidation(schema),
    handler: async (req, reply) => {

        const data = {}

        reply.send(data)

    }
})

preHandler will validate your req before the handler

In that example, I’m using that schema as a Mongoose schema as well

@Michael-Liendo Michael-Liendo self-assigned this Aug 7, 2024
@Michael-Liendo
Copy link
Owner Author

tode in #22

@Michael-Liendo Michael-Liendo linked a pull request Aug 7, 2024 that will close this issue
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

Successfully merging a pull request may close this issue.

1 participant