forked from prsaya/node-express-mongodb-html-demo-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
92 lines (78 loc) · 1.98 KB
/
Copy pathserver.js
File metadata and controls
92 lines (78 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const express = require("express")
const cors = require("cors")
const database = require('./database')
const dbFunctions = require('./dbFunctions')
const { ObjectId } = require("mongodb")
const port = 3000
const app = express()
app.use(cors())
app.use(express.static("public"))
app.use(express.json())
// The route definitions for get, post and delete
app.get("/api/allnames", async (req, res) => {
try {
const docs = await dbFunctions.getAllDocs()
res.json(docs)
}
catch (err) {
console.error("# Get Error", err)
res.status(500).send({ error: err.name + ", " + err.message })
}
})
app.post('/api/addname', async (req, res) => {
let data = req.body;
try {
data = await dbFunctions.addDoc(data)
res.json(data)
}
catch (err) {
console.error("# Post Error", err)
res.status(500).send({ error: err.name + ", " + err.message })
}
});
app.delete("/api/deletename/:id", async (req, res) => {
const id = req.params.id
let respObj = {}
if (id && ObjectId.isValid(id)) {
try {
respObj = await dbFunctions.deleteDoc(id)
}
catch (err) {
console.error("# Delete Error", err)
res.status(500).send({ error: err.name + ", " + err.message })
return
}
}
else {
respObj = { message: "Data not deleted; the id to delete is not valid!" }
}
res.json(respObj)
})
// Start the web server and connect to the database
let server
let conn
(async () => {
try {
conn = await database()
await dbFunctions.getDb(conn)
server = app.listen(port, () => {
console.log("# App server listening on port " + port)
})
}
catch(err) {
console.error("# Error:", err)
console.error("# Exiting the application.")
await closing()
process.exit(1)
}
})()
async function closing() {
console.log("# Closing resources...")
if (conn) {
await conn.close()
console.log("# Database connection closed.")
}
if (server) {
server.close(() => console.log("# Web server stopped."))
}
}