forked from r-spacex/SpaceX-API
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
66 lines (51 loc) · 1.4 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const conditional = require('koa-conditional-get');
const etag = require('koa-etag');
const cors = require('koa2-cors');
const helmet = require('koa-helmet');
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const mongoose = require('mongoose');
const { logger } = require('./middleware/logger');
const { responseTime, errors } = require('./middleware');
const routes = require('./routes');
const app = new Koa();
mongoose.connect(process.env.SPACEX_MONGO, {
bufferCommands: false,
});
const db = mongoose.connection;
db.on('error', (err) => {
logger.error(err);
});
db.once('connected', () => {
logger.info('Mongo connected');
app.emit('ready');
});
db.on('reconnected', () => {
logger.info('Mongo re-connected');
});
db.on('disconnected', () => {
logger.info('Mongo disconnected');
});
// disable console.errors for pino
app.silent = true;
// Error handler
app.use(errors);
app.use(conditional());
app.use(etag());
app.use(bodyParser());
// HTTP header security
app.use(helmet());
// Enable CORS for all routes
app.use(cors({
origin: '*',
allowMethods: ['GET', 'POST', 'PATCH', 'DELETE'],
allowHeaders: ['Content-Type', 'Accept'],
exposeHeaders: ['spacex-api-cache', 'spacex-api-response-time'],
}));
// Set header with API response time
app.use(responseTime);
// Request logging
// app.use(requestLogger);
// Register routes
app.use(routes());
module.exports = app;