-
Notifications
You must be signed in to change notification settings - Fork 0
/
gracefulShutdown.js
75 lines (58 loc) · 1.81 KB
/
gracefulShutdown.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
import { MongoClient } from 'mongodb'
import http from 'node:http'
import { setTimeout } from 'node:timers/promises'
import { promisify } from 'node:util'
async function dbConnect() {
const client = new MongoClient('mongodb://localhost:27017')
await client.connect()
console.log('mongodb is connected')
const db = client.db('comics')
return {
collections: { heroes: db.collection('heroes') },
client,
}
}
const { client, collections } = await dbConnect()
async function handler(request, response) {
for await (const data of request) {
try {
const hero = JSON.parse(data)
await collections.heroes.insertOne({
...hero,
updatedAt: new Date().toISOString(),
})
const heroes = await collections.heroes.find().toArray()
await setTimeout(10000)
response.writeHead(200)
response.write(JSON.stringify(heroes))
} catch (error) {
console.log('a request error has happened', error)
response.writeHead(500, { 'Content-Type': 'application/json' })
response.write(JSON.stringify({ message: 'internal server error ' }))
} finally {
response.end()
}
}
}
// await client.close()
/**
* curl -i localhost:3000 -X POST --data '{"name": "Batman", "age": "80"}'
*/
const server = http
.createServer(handler)
.listen(3000, () =>
console.log('server is running at port 3000', process.pid),
)
// SIGINT -> ctrl + c
// SIGTERM => KILL
const onStop = async (signal) => {
console.info(`\n${signal} signal received.`)
console.log('Closing http server')
await promisify(server.close.bind(server))()
console.log('http server has closed')
console.log('Closing mongodb client')
await client.close()
console.log('mongodb has closed')
process.exit(0)
}
;['SIGINT', 'SIGTERM'].forEach((event) => process.on(event, onStop))