Aquila169 / zod-express-middleware

Express middleware to validate requests using zod schema's.
MIT License
86 stars 13 forks source link

[Help] Usage with already Custom Typed Express Request type #2

Open OmkarK45 opened 2 years ago

OmkarK45 commented 2 years ago

Hi there! Thank you for creating this middleware. I'm using express-session and have attached user object to express request.

export interface ExpressRequest extends Request {
    user?: User
}

However, when I type my request to Express request, I lose all the typesafety provided by this plugin.

router.get('/foo', validateRequestBody(SomeZodSchema), async (req : ExpressRequest, res)=> { 
            const user = req.user 
            const { foo } = req.body // not typesafe 
} )

any help would be appreciated 😄

RomainCscn commented 2 years ago

Hello @OmkarK45, just curious, did you find a solution / workaround for this issue?

OmkarK45 commented 2 years ago

Hello @OmkarK45, just curious, did you find a solution / workaround for this issue?

Unfortunately, no..

Drarig29 commented 2 years ago

Hi! You shouldn't force req to be of type ExpressRequest in your request handlers.

You can use global declaration merging instead. So that the Request type is changed globally to have your user?: User type.

Add a global.d.ts at the root of your project and inside, put the following:

import { User } from './path/to/User';

declare global {
  namespace Express {
    interface Request {
      user?: User,
    }
  }
}

With this, when you will import { Request } from 'express', you'll have the user property directly in it. So you'll be able to use async (req, res) => { } like before, without specifying the type of req, and it should remain "custom typed".