forked from przemekulik/nodetours
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
executable file
·76 lines (72 loc) · 2.35 KB
/
server.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
67
68
69
70
71
72
73
74
75
76
// npm pacakages
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const { ApolloServer, gql } = require('apollo-server-express');
// app imports
const rootRouter = require('./routers/root');
const cruisesRouter = require('./routers/cruises');
const bookingsRouter = require('./routers/bookings');
const customersRouter = require('./routers/customers');
const init = require('./utilities/init');
const logger = require('./utilities/loggers');
const typeDefs = fs.readFileSync('./data/schema.graphql',{encoding: 'utf-8'});
const resolvers = require('./routers/graphql');
//globals
app = express();
app.use(bodyParser.json());
app.use('/', rootRouter);
app.use('/cruises', cruisesRouter);
app.use('/bookings', bookingsRouter);
app.use('/customers', customersRouter);
const server = new ApolloServer({
typeDefs,
resolvers,
graphiql: true,
context: ({ req }) => {
const locale = req.headers.locale;
return { locale };
}
});
server.applyMiddleware({ app });
// Set up Mongo DB connection and start the app
init.setDBConnectionString(process);
const MongoClient = require('mongodb').MongoClient;
const url = `mongodb://${dbhost}:${dbport}`;
const dbName = 'nodetours';
const dbClient = new MongoClient(url+dbName, { useUnifiedTopology: true, poolSize: 10 });
dbClient.connect(function (err) {
if (err) {
logger.error(`Startup: Database connection could not be established. The app will exit.`);
logger.error(` Error: ${error}`);
process.exit();
} else {
db = dbClient.db(dbName);
logger.verbose(`Startup: Database connection established`);
// initialize db if not present
init.initDB(db);
// start server
app = app.listen(process.env.PORT || 7777, function () {
globalThis.host = require('os').hostname();
globalThis.port = '7777';
logger.verbose(`Startup: NodeTours listening at http://${host}:${port}`);
});
}
});
// Close db connection when interrupted
// SIGINT e.g. Ctrl+C
process.on('SIGINT', () => {
app.close(() => {
logger.info(`Received SIGINT. Closing DB connections and exiting`);
MongoClient(url).close();
process.exit();
})
});
//SIGTERM e.g. kill without -9
process.on('SIGTERM', () => {
app.close(() => {
logger.info(`Received SIGTERM. Closing DB connections and exiting`);
MongoClient(url).close();
process.exit();
})
});