-
Notifications
You must be signed in to change notification settings - Fork 187
/
Copy pathapi.js
61 lines (52 loc) · 1.66 KB
/
api.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
50
51
52
53
54
55
56
57
58
59
60
61
/**
* third party libraries
*/
const bodyParser = require('body-parser');
const express = require('express');
const helmet = require('helmet');
const http = require('http');
const mapRoutes = require('express-routes-mapper');
const cors = require('cors');
/**
* server configuration
*/
const config = require('../config/');
const dbService = require('./services/db.service');
const auth = require('./policies/auth.policy');
// environment: development, staging, testing, production
const environment = process.env.NODE_ENV;
/**
* express application
*/
const app = express();
const server = http.Server(app);
const mappedOpenRoutes = mapRoutes(config.publicRoutes, 'api/controllers/');
const mappedAuthRoutes = mapRoutes(config.privateRoutes, 'api/controllers/');
const DB = dbService(environment, config.migrate).start();
// allow cross origin requests
// configure to only allow requests from certain origins
app.use(cors());
// secure express app
app.use(helmet({
dnsPrefetchControl: false,
frameguard: false,
ieNoOpen: false,
}));
// parsing the request bodys
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// secure your private routes with jwt authentication middleware
app.all('/private/*', (req, res, next) => auth(req, res, next));
// fill routes for express application
app.use('/public', mappedOpenRoutes);
app.use('/private', mappedAuthRoutes);
server.listen(config.port, () => {
if (environment !== 'production' &&
environment !== 'development' &&
environment !== 'testing'
) {
console.error(`NODE_ENV is set to ${environment}, but only production and development are valid.`);
process.exit(1);
}
return DB;
});