Skip to content

Commit

Permalink
add midlewares
Browse files Browse the repository at this point in the history
  • Loading branch information
patchamama committed Sep 9, 2023
1 parent a6b0575 commit 7c91330
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
6 changes: 6 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const express = require('express')
const app = express()
const cors = require('cors')
const BlogsRouter = require('./controllers/blogs')
const middleware = require('./utils/middleware')
const logger = require('./utils/logger')
const mongoose = require('mongoose')
mongoose.set('strictQuery', false)
Expand All @@ -19,8 +20,13 @@ mongoose
})

app.use(cors())
app.use(express.static('build'))
app.use(express.json())
app.use(middleware.requestLogger)

app.use('/api/blogs', BlogsRouter)

app.use(middleware.unknownEndpoint)
app.use(middleware.errorHandler)

module.exports = app
31 changes: 31 additions & 0 deletions utils/middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const logger = require('./logger')

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: 'unknown 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,
}

0 comments on commit 7c91330

Please sign in to comment.