-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathserver.ts
More file actions
77 lines (65 loc) · 1.98 KB
/
server.ts
File metadata and controls
77 lines (65 loc) · 1.98 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
import https from 'https'
import http from 'http'
import fs from 'fs'
import express, { Express } from 'express'
import session from 'express-session'
import routes from './routes/index.js'
const router: Express = express()
const isDevelopment = process.env.NODE_ENV === 'development'
// SSL certificate (development only)
let credentials: { key: string; cert: string } | undefined
if (isDevelopment) {
const privateKey = fs.readFileSync('../certs/key.pem', 'utf8')
const certificate = fs.readFileSync('../certs/cert.pem', 'utf8')
credentials = { key: privateKey, cert: certificate }
}
router.use(express.urlencoded({ extended: true }))
router.use(express.json())
// Session middleware
router.use(
session({
secret: process.env.SESSION_COOKIE_SECRET_KEY || 'supersecretilpaystring',
resave: false,
saveUninitialized: true, // Only save the session if it is modified
cookie: {
httpOnly: true,
secure: true,
sameSite: 'none'
}
})
)
router.use((req, res, next) => {
// set the CORS policy
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Credentials', 'true')
res.header(
'Access-Control-Allow-Headers',
'origin,X-Requested-With,Content-Type,Accept,Authorization'
)
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE')
return res.status(200).json({})
}
next()
})
router.use('/', routes)
/** Error handling */
router.use((_, res) => {
const error = new Error('not found')
return res.status(404).json({
message: error.message
})
})
// Start that server
const PORT: string | number = process.env.PORT ?? 5101
if (isDevelopment && credentials) {
const httpsServer = https.createServer(credentials, router)
httpsServer.listen(PORT, () =>
console.log(`Https API server started on port ${PORT}`)
)
} else {
const httpServer = http.createServer(router)
httpServer.listen(PORT, () =>
console.log(`HTTP API server started on port ${PORT}`)
)
}