Created
October 17, 2018 19:36
-
-
Save markmur/10a5509788c6ff9061965f1cb23d34d1 to your computer and use it in GitHub Desktop.
Custom Express Responses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Create custom response | |
| * @param {Object} res - express response object | |
| * @param {Number} status - status code | |
| * @param {String} defaultMessage - default response | |
| * @returns {Function} returns function which access response message | |
| */ | |
| const createResponse = (res, status, defaultMessage) => data => { | |
| // Set status code | |
| res.status(status) | |
| if (typeof data === 'string') { | |
| return res.json({ | |
| message: data | |
| }) | |
| } | |
| return res.json( | |
| data || { | |
| message: defaultMessage | |
| } | |
| ) | |
| } | |
| app.use((req, res, next) => { | |
| res.notFound = createResponse(res, 404, 'Not Found') | |
| res.unauthorized = createResponse(res, 401, 'Unauthorized') | |
| res.badRequest = createResponse(res, 400, 'Bad Request') | |
| res.serverError = createResponse(res, 500, 'Internal Server Error') | |
| return next() | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment