-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
49 lines (41 loc) · 2.16 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
const express = require('express')
const app = express()
const cors = require('cors')
const { response } = require('express')
require('express-async-errors')
const blogsRouter = require('./controllers/blogs')
const config = require('./utils/config')
const mongoose = require('mongoose')
const loginRouter = require('./controllers/login')
const logger = require('./utils/logger')
const middleware = require('./utils/middleware')
// define a separate router for dealing with users
const usersRouter = require('./controllers/users')
const mongoUrl = config.MONGODB_URI
mongoose.connect(mongoUrl)
// Use app.use to load the different middlewares into the express application
// cors middleware to use and allow for requests from all origins
app.use(cors())
// In order to access the data easily, we need the help of the express json-parser
// Without the json-parser i.e. json(), the body property of request object sent through post request would be undefined.
app.use(express.json())
// Middleware functions are called in the order that they're taken into use with the express server object's use hence the json parser is above this
app.use(middleware.requestLogger)
// middleware should take the token from the Authorization header and place it to the token field of the request object
app.use(middleware.tokenExtractor)
// The blogsRouter we defined in ./controller/blogs is used if the URL of the request starts with '/api/blogs'
app.use('/api/blogs', blogsRouter)
// The loginRouter we defined in ./controller/login is used if the URL of the request starts with '/api/login'
app.use('/api/login', loginRouter)
// The usersRouter we defined in ./controller/users is used if the URL of the request starts with '/api/users'
app.use('/api/users', usersRouter)
// API endpoints to the backend for the testingRouter We can empty the database using these endpoints & to take them into use
if(process.env.NODE_ENV === 'test') {
const testingRouter = require('./controllers/testing')
app.use('/api/testing', testingRouter)
}
// handler of requests with unknown endpoint
app.use(middleware.unknownEndpoint)
// this has to be the last loaded middleware
app.use(middleware.errorHandler)
module.exports = app