-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserverTodos.js
More file actions
65 lines (53 loc) · 1.29 KB
/
serverTodos.js
File metadata and controls
65 lines (53 loc) · 1.29 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
import { createServer } from "node:http"
import { index, remove, update, write } from "./api/todos-foo.js"
import { NotFounfError } from "./api/errorClass.js"
import { createReadStream } from "node:fs"
const port = process.env.PORT || 3500
const todoServer = createServer(async function (req, res) {
try {
const url = new URL(req.url, `http://${req.headers.host}
`)
res.setHeader("Content-Type", "application/json")
const endpoint = `${req.method}:${url.pathname}`
// console.log(endpoint)
let result
switch (endpoint) {
case "GET:/":
res.setHeader("Content-Type", "text/html")
console.log(endpoint)
createReadStream("index.html").pipe(res)
return
case "GET:/todos":
result = await index(req, res)
break;
case "POST:/todos":
result = await write(req, res)
break;
case "DELETE:/todos":
await remove(req, res, url)
case "PATCH:/todos":
await update(req, res, url)
break;
default:
break;
}
if (result) {
res.write(JSON.stringify(result))
}
} catch (err) {
if (err instanceof NotFounfError) {
res.statusCode = 404
res.write("todo Not found")
return
}
res.statusCode = 500
throw err
}
fina
res.end()
}
)
todoServer.listen(port, function () {
console.log("todo server is running on port ",
port)
})