I am currently working on developing a new 'common' module for my team. One of the key features it should have is an extension of both the response and request objects in Express.
Our main goal is to achieve two things - first, extending the Request object to include a user property that will be initialized by a middleware responsible for authentication.
The second objective is to establish a consistent error handling convention. To achieve this, I plan to extend the response type of Express by adding a method called sendError. This method will take an exception or error message as input and generate the appropriate response. I want to go beyond simply extending an interface; I aim to provide implementation as well.
Thus far, I have created a new module where I added a file named types.d.ts and included it in my "types" section within the tsconfig.
import {User} from '../models/user.ts'
declare module 'express'{
export interface Request {
user: User;
}
}
Within my module, I can successfully access the user property for requests, and everything functions smoothly. However, when another service installs this module via npm, it fails to recognize this property.
My second question pertains to achieving our secondary goal. This task involves more than just extending an interface; it resembles extending a class since I wish to provide implementation details.
One solution I considered is outlined below:
import {User} from '../models/user.ts'
declare module 'express'{
export interface Response {
sendError: (statusCode : number, error : Error ) => void;
}
}
express.Response.sendError = //insert custom logic here