forked from dewald-els/noroff-assignment-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
42 lines (30 loc) · 1 KB
/
index.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
// server.js
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
const {PORT = 3000} = process.env
if (process.env.NODE_ENV !== 'PRODUCTION') {
require('dotenv').config()
}
const HTTP_METHOD_GET = 'get'
server.use(middlewares)
server.use((request, response, next) => {
if (request.method.toLowerCase() !== HTTP_METHOD_GET) {
const token = request.headers['x-api-key'] || ''
if (!token) {
return response.status('401').json({error: 'You are not allowed to access this resource'})
}
const key = process.env.API_KEY
if (token === key) {
return next()
} else {
return response.status('401').json({error: 'Invalid API Key provided - are not allowed to access this resource'})
}
}
next()
})
server.use(router)
server.listen(PORT, () => {
console.log('JSON Server is running in port: ' + PORT)
})