trackmyd-api/server.js

60 lines
1.4 KiB
JavaScript
Raw Normal View History

2019-02-19 18:56:25 +01:00
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
2019-02-20 12:48:32 +01:00
const basicAuth = require('express-basic-auth');
2019-02-19 18:56:25 +01:00
const config = require('./config');
2019-02-20 11:09:57 +01:00
const logger = require('./logger');
2019-02-19 19:21:19 +01:00
const apiRoutes = require('./apiRoutes');
2019-02-19 18:56:25 +01:00
const { db } = config;
const app = express();
const port = process.env.PORT || config.app.port;
const connectionString = `${db.prefix}${db.user}:${db.password}@${db.host}/${db.database}`;
mongoose.connect(connectionString, { useNewUrlParser: true });
mongoose.set('useFindAndModify', false);
2019-02-22 10:12:24 +01:00
const mongodb = mongoose.connection;
2019-02-20 13:48:08 +01:00
app.use((err, req, res, next) => {
logger.logError(err);
res.status(500);
next();
});
app.use(basicAuth({ users: config.app.auth.users }));
2019-02-19 19:21:19 +01:00
app.use(bodyParser.urlencoded({ extended: true }));
2019-02-19 18:56:25 +01:00
app.use(bodyParser.json());
2019-02-19 19:21:19 +01:00
app.use('/api', apiRoutes);
2019-02-19 18:56:25 +01:00
app.listen(port, () => {
2019-02-20 11:09:57 +01:00
logger.logInfo('Server started.');
logger.logConsole('Server started.');
});
2019-02-22 10:12:24 +01:00
mongodb.on('connected', () => {
logger.logInfo('DB connected');
});
mongodb.on('disconnected', () => {
logger.logInfo('DB disconnected');
});
mongodb.on('error', (err) => {
logger.logError(`DB error:' ${err}`);
});
2019-02-20 11:09:57 +01:00
process.on('uncaughtException', (err) => {
logger.logError(err);
});
process.on('SIGINT', () => {
2019-02-22 10:12:24 +01:00
mongoose.disconnect();
2019-02-20 11:09:57 +01:00
logger.logInfo('Server stopped');
logger.logConsole('Server stopped');
process.exit(0);
2019-02-19 19:21:19 +01:00
});