-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
85 lines (73 loc) · 2.29 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
77
78
79
80
81
82
83
/**
* This module initiates the server.
*
* @module server
* @author Xulong Zeng
*/
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import morgan from 'morgan';
import { getTodolist, getTodo, postTodo, deleteTodo, patchTodo, getTodoSwr } from './app/routes/todo';
import { URL_DB } from './utils/constants/urls';
/**
* The application runs on Express, initiate an Express instance here first.
* @type Express
*/
const app = express();
// The port to listen on
const port = process.env.PORT || 8080;
// Database configuration
const options = {
server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 1, connectTimeoutMS : 30000 } }
};
mongoose.Promise = global.Promise;
mongoose.connect( URL_DB, options );
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
/**
* bodyParser middleware for extracting the body of a request
* morgan middleware as http request logger
*/
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.use(morgan('dev'));
// point to static asset
app.use(express.static(__dirname + '/client/dist'));
/**
* A self-defined middleware
* enabling http requests from webpack-dev-server
*/
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,POST,DELETE,PATCH');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
/**
* Define api routes here.
*
* GET/todolist get all todos
* GET/todolist/:id get a single todo by id
* GET/swr/:id get the stopword-removal result of a todo by id
* POST/todolist create a new todo
* DELETE/todolist/:id delete a todo by id
* PATCH/todolist/:id update a todo by id
*/
app.route('/todolist')
.get(getTodolist)
.post(postTodo);
app.route('/todolist/:id')
.get(getTodo)
.delete(deleteTodo)
.patch(patchTodo);
app.route('/swr/:id')
.get(getTodoSwr);
// handle all other request with homepage content
app.route('*').get((req, res) => {
res.sendFile('client/dist/index.html', { root: __dirname });
});
// Start listening on port
app.listen(port);
console.log(`server listening on port ${port}`);