opt-cc/api/server.js

156 lines
5.4 KiB
JavaScript
Raw Normal View History

2018-03-12 09:26:44 +01:00
'use strict';
2017-05-10 11:04:06 +02:00
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const bodyParser = require('body-parser');
const requestLogger = require('morgan');
2018-02-04 15:58:28 +01:00
2018-04-02 00:32:45 +02:00
// logger
2018-02-04 15:58:28 +01:00
const debug = require('debug');
const error = debug('cc:server:err');
const logger = debug('cc:server');
logger.log = console.log.bind(console);
2018-03-12 09:26:44 +01:00
const cors = require('cors');
2017-05-10 11:04:06 +02:00
const mongoose = require('mongoose');
2018-04-02 00:32:45 +02:00
const {exec} = require('child_process');
2017-05-10 11:04:06 +02:00
// own modules
const config = require('./config/config');
const urls = require('./config/api-url');
2017-05-10 11:04:06 +02:00
const restAPIchecks = require('./middleware/request-checks.js');
const errorResponseWare = require('./middleware/error-response');
const apiAuthenticationMiddleware = require('./middleware/auth-middleware');
2017-06-08 13:14:53 +02:00
const checkAdmin = require('./middleware/permission-check').checkAdmin;
2017-07-23 11:07:47 +02:00
const signatureCronJob = require('./cron-job/cron').cronJobSignature;
const backupCronJob = require('./cron-job/cron').cronJobBackup;
2017-07-15 12:03:38 +02:00
2017-05-10 11:04:06 +02:00
// router modules
const authenticateRouter = require('./routes/authenticate');
2017-06-08 19:46:36 +02:00
const accountRouter = require('./routes/account');
2017-05-10 11:04:06 +02:00
const overviewRouter = require('./routes/overview');
const userRouter = require('./routes/users');
const squadRouter = require('./routes/squads');
const rankRouter = require('./routes/ranks');
const decorationRouter = require('./routes/decorations');
const awardingRouter = require('./routes/awardings');
2017-06-09 18:30:35 +02:00
const requestRouter = require('./routes/request');
2017-10-01 13:12:55 +02:00
const playerRouter = require('./routes/players');
2017-05-10 11:04:06 +02:00
const signatureRouter = require('./routes/signatures');
const commandRouter = require('./routes/command');
2017-08-12 16:28:18 +02:00
const campaignRouter = require('./routes/campaigns');
2017-07-08 22:50:01 +02:00
const warRouter = require('./routes/wars');
const logRouter = require('./routes/logs');
2017-05-10 11:04:06 +02:00
// Configuration ***********************************
// mongoose promise setup
mongoose.Promise = global.Promise;
// app creation
const app = express();
// Middlewares *************************************************
2017-05-16 12:55:53 +02:00
// setup CORS-middleware
const corsOptions = {
methods: ['GET'],
2018-03-12 09:26:44 +01:00
optionsSuccessStatus: 200,
2017-05-16 12:55:53 +02:00
};
app.use(cors(corsOptions));
app.use(favicon(path.join(__dirname + '/..', 'public', 'favicon.ico')));
app.use(express.static(path.join(__dirname + '/..', 'public')));
2017-07-09 11:49:21 +02:00
app.use(bodyParser.json({limit: '10mb'}));
app.use(bodyParser.urlencoded({limit: '10mb', extended: true}));
2017-05-10 11:04:06 +02:00
// API request checks for API-version and JSON etc.
app.use(restAPIchecks);
// Routes ******************************************************
app.use(urls.signatures, signatureRouter);
2017-05-10 11:04:06 +02:00
2017-06-08 13:14:53 +02:00
// initialize logging at this point to exclude /signature requests
2017-05-23 13:26:26 +02:00
if (process.env.NODE_ENV === config.dev.env) {
// development logging
app.use(requestLogger('dev'));
2018-03-30 17:26:09 +02:00
} else if (process.env.NODE_ENV !== config.test.dredd.env && process.env.NODE_ENV !== config.test.unit.env) {
// production logging, apache style
2017-07-16 14:16:24 +02:00
app.use(requestLogger(':date[clf] :method :url :response-time ms :status'));
}
app.use(urls.auth, authenticateRouter);
app.use(urls.overview, overviewRouter);
app.use(urls.users, userRouter);
app.use(urls.squads, squadRouter);
app.use(urls.ranks, rankRouter);
app.use(urls.decorations, decorationRouter);
app.use(urls.request, requestRouter);
2017-06-09 18:30:35 +02:00
app.use(urls.awards, awardingRouter);
app.use(urls.wars, warRouter);
2017-10-01 13:12:55 +02:00
app.use(urls.players, playerRouter);
2018-02-04 15:58:28 +01:00
app.use(urls.campaigns, campaignRouter);
app.use(urls.logs, logRouter);
2017-06-08 13:14:53 +02:00
app.use(urls.command, apiAuthenticationMiddleware, checkAdmin, commandRouter);
2017-06-08 19:46:36 +02:00
app.use(urls.account, apiAuthenticationMiddleware, checkAdmin, accountRouter);
2017-05-10 11:04:06 +02:00
// send index.html on all different paths
2018-03-20 10:48:00 +01:00
app.use((req, res) => {
2018-03-12 09:26:44 +01:00
res.sendFile('public/index.html', {root: __dirname + '/..'});
2017-05-10 11:04:06 +02:00
});
// register error handlers
errorResponseWare(app);
// Start the server
2018-04-02 00:32:45 +02:00
if (process.env.NODE_ENV === config.test.unit.env || process.env.NODE_ENV === config.test.dredd.env) {
2018-03-30 17:26:09 +02:00
const MongodbMemoryServer = require('mongodb-memory-server').default;
const mongoServer = new MongodbMemoryServer();
mongoose.Promise = Promise;
mongoServer.getConnectionString().then((mongoUri) => {
2018-03-30 18:16:52 +02:00
mongoose.connect(mongoUri);
2018-03-30 17:26:09 +02:00
mongoose.connection.on('error', (e) => {
if (e.message.code === 'ETIMEDOUT') {
2018-03-30 18:16:52 +02:00
error(e);
2018-04-02 00:32:45 +02:00
mongoose.connect(mongoUri);
2018-03-30 17:26:09 +02:00
}
2018-03-30 18:16:52 +02:00
error(e);
2018-03-30 17:26:09 +02:00
});
2018-04-02 00:32:45 +02:00
if (process.env.NODE_ENV === config.test.dredd.env) {
const mongoPortAndDB = mongoUri.replace('mongodb://localhost:', '').split('/');
exec(__dirname + '/apib/dredd/populate-data.sh'
.concat(' -p ').concat(mongoPortAndDB[0])
.concat(' -d ').concat(mongoPortAndDB[1]), (err, stdout, stderr) => {
if (err) {
error(err.message);
} else {
logger('\x1b[32m%s\x1b[0m', stderr);
}
});
}
2018-03-30 17:26:09 +02:00
mongoose.connection.once('open', () => {
2018-03-30 18:16:52 +02:00
logger(`MongoDB successfully connected to ${mongoUri}`);
2018-04-02 00:32:45 +02:00
app.listen(config.test.port);
logger('Listening on port ' + config.test.port);
2018-03-30 17:26:09 +02:00
});
});
2018-04-02 00:32:45 +02:00
} else {
2018-03-30 17:26:09 +02:00
const mongoosePromise = mongoose.connect(config.database.uri + config.database.db);
mongoosePromise.then((db) => {
app.listen(config.port, (err) => {
if (err !== undefined) {
error('Error on startup, ', err);
} else {
logger('Listening on port ' + config.port);
signatureCronJob.start();
backupCronJob.start();
}
});
});
2017-05-10 11:04:06 +02:00
}
module.exports = app;