express-methods
v1.1.4
Published
This project is build in TypeScript, demonstrates standard usage of express framework with advance custom request methods and error generators
Downloads
19
Readme
Express Methods
This project is build in TypeScript, demonstrates standard usage of express framework with advance custom request methods and error generators
Run application in Production mode
npm start
Run application in Development mode [ Configured with Nodemon ]
npm run dev
Finish Method
Finish method makes use of send method under the hood, finish method allows to send http response in a uniform pattern for all the APIS including success and failure response
const attachFinishMethod = (req: Request, res: ExpressResponse, next) => {
let defaultHttpStatus = 200;
if (req.method !== httpMethod.GET) {
defaultHttpStatus = 201;
}
res.finish = (data = {}, message = "", httpStatus = defaultHttpStatus, errors = {}) => {
res.status(httpStatus).send({
message,
data,
errors
});
};
next();
};
Make sure to add this middleware on highest scope of application, this will make sure to attach finish method to every request
app.use(attachFinishMethod);
Example for usage of finish method
app.get("/", (req, res: ExpressResponse, next) => {
try {
const result = {
isUser: true
};
res.finish(result, "Fetched mock user info!");
} catch (error) {
next(error);
}
});
Error Generators
ExpressError is build on top of Error constructor it adds ability to send custom http message and status code
throw new ExpressError("Its Forbidden", 403);
throw new httpError.Forbidden();
Make sure to place this middleware at the end of scope, this middleware is compatible with both the error generators shown above
app.use(expressErrorHandler);