aboutsummaryrefslogtreecommitdiff
path: root/part4/blog/utils
diff options
context:
space:
mode:
Diffstat (limited to 'part4/blog/utils')
-rw-r--r--part4/blog/utils/logger.js11
-rw-r--r--part4/blog/utils/middleware.js32
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
+}