-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocalServer.js
More file actions
86 lines (75 loc) · 2.01 KB
/
localServer.js
File metadata and controls
86 lines (75 loc) · 2.01 KB
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
84
85
86
import compression from 'compression';
import cors from 'cors';
import express from 'express';
import session from 'express-session';
import https from 'https';
import { GUEST_ID, SESSION_TTL, getTls, secret, token } from './global.cjs';
import initDb from './mongodb/index.js';
import connectDb from './mongodb/session.js';
import filesRoute from './routes/files/index.js';
import todosRoute from './routes/todos/index.js';
import usersRoute from './routes/users/index.js';
const PORT = 444;
async function createServer() {
const app = express();
/* initialize mongodb
只在第一次运行程序时初始化数据库的collection和expired字段,并不是打开也不是连接db
*/
await initDb();
/* CORS */
app.use(
cors({
origin: true,
credentials: true,
})
);
/* session middleware */
app.use(
session({
secret,
store: new (connectDb(session))(undefined, SESSION_TTL),
resave: false,
saveUninitialized: false,
cookie: {
maxAge: SESSION_TTL,
secure: true,
sameSite: 'strict',
},
})
);
/* compression */
app.use(compression());
/* parse json */
app.use(express.json());
/* static */
app.use('/client', express.static('./dist/client', { index: false }));
/* api routes */
const apiRouter = express.Router();
/* validate token and initialize userId */
apiRouter.use((req, res, next) => {
if (req.get('token') !== token) {
return res.end();
}
if (req.session.userId === undefined) {
req.session.userId = GUEST_ID;
}
next();
});
usersRoute(apiRouter);
todosRoute(apiRouter);
filesRoute(apiRouter);
app.use('/api', apiRouter);
/* ssr */
//pagesRoute(app)
/* error handler */
// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
res.status(500).send(err.stack);
});
return https.createServer(getTls(), app);
}
createServer().then((app) => {
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
});