diff options
author | Ibrahim Mkusa <ibrahimmkusa@gmail.com> | 2023-06-18 20:26:14 -0400 |
---|---|---|
committer | Ibrahim Mkusa <ibrahimmkusa@gmail.com> | 2023-06-18 20:26:14 -0400 |
commit | 81c9e17aebc95f0939c5b636ca64af9d47dfc992 (patch) | |
tree | 98388d586729b513eee9f975a5819cc6078874e2 /part4/blog/utils | |
parent | 13ca52505d4a247f72c5fad8161dc497da6da368 (diff) |
ex4.2 tackling complexity via modularity
Diffstat (limited to 'part4/blog/utils')
-rw-r--r-- | part4/blog/utils/logger.js | 11 | ||||
-rw-r--r-- | part4/blog/utils/middleware.js | 32 |
2 files changed, 43 insertions, 0 deletions
diff --git a/part4/blog/utils/logger.js b/part4/blog/utils/logger.js new file mode 100644 index 0000000..f4b4c78 --- /dev/null +++ b/part4/blog/utils/logger.js @@ -0,0 +1,11 @@ +const info = (...params) => { + console.log('info: ', ...params) +} + +const error = (...params) => { + console.log('error: ', ...params) +} + +module.exports = { + info, error +} diff --git a/part4/blog/utils/middleware.js b/part4/blog/utils/middleware.js new file mode 100644 index 0000000..1b2979a --- /dev/null +++ b/part4/blog/utils/middleware.js @@ -0,0 +1,32 @@ +const logger = require('./logger.js') + +const requestLogger = (request, response, next) => { + logger.info('Method:', request.method) + logger.info('Path: ', request.path) + logger.info('Body: ', request.body) + logger.info('---') + next() +} + +const unknownEndpoint = (request, response) => { + response.status(404).send({ error: 'unkown endpoint' }) +} + +const errorHandler = (error, request, response, next) => { + logger.error(error.message) + + if (error.name === 'CastError') { + return response.status(400).send( {error: 'malformatted id'} ) + + } else if (error.name === 'ValidationError') { + return response.status(400).json({error: 'error.message'}) + } + + next(error) +} + +module.exports = { + requestLogger, + unknownEndpoint, + errorHandler +} |