mm-ninja-turtles / turtle-express

My attempt of making Express.JS a typesafe router with Zod.
3 stars 0 forks source link

[bug]: in request validation #57

Closed PyaePhyoKyaw61194 closed 2 years ago

PyaePhyoKyaw61194 commented 2 years ago

I tested this kind of example with request body


const users = router.path('/users')

users.handler({
    id: 'CreateNewUser',
    method: 'post',
    request: {
        body: z.object({
            name: z.string().min(1, { message: 'name is required.' }),
            email: z.string().email({ message: 'wrong email format.' }),
        }),
    },
    response: {
        200: z.object({
            name: z.string(),
            email: z.string().email(),
        }),
    },
    async resolver({ ctx }) {
        const { name, email } = ctx.body
        const user = await db.users.create({ name, email })
        return {
            200: user,
        }
    },
})
'''
PyaePhyoKyaw61194 commented 2 years ago

I got 500 internal server error even though I put the name and email for body.

The Response

{
  "success": false,
  "message": "Something went wrong!",
  "data": null,
  "error": "[case `resolver`]: Invalid state"
}

The Request Body (tested in Thunder Client)

{
 "name": "Mg Mg",
 "email" : "mgmg@gmail.com"
}
PyaePhyoKyaw61194 commented 2 years ago

Another test is , I added query validation( without body validation ) this time.

request: {
        query: z.object({
            limit: z.string(),
        }),
    },

I got the same error response if the zod validation is failed. (I did not add limit query string)

{
  "success": false,
  "message": "Something went wrong!",
  "data": null,
  "error": "[case `resolver`]: Invalid state"
}

Last time I checked , I think the error message is a bit more explicit zod error message like "limit is required " (same meaning like this).

PyaePhyoKyaw61194 commented 2 years ago

@mm-ninja-turtles/core-maintainers

PyaePhyoKyaw61194 commented 2 years ago

@wai-lin The problem is solved by adding router.use(express.json()) before router.setup({})

wai-lin commented 2 years ago

@PyaePhyoKyaw61194

I've updated the getting started guide. please read and do as it is.

From v0.2.0, setup function only the route setup of paths. No more extra works. Which mean it doesn't enable express.json() or express.urlencoded() by default. Giving the user the full control of the app setup.

If this is resolved as you've said, I'll close this issue.