-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
54 lines (50 loc) · 1.56 KB
/
server.js
File metadata and controls
54 lines (50 loc) · 1.56 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
import http from 'http'
import { log, logError } from './utils.js'
import {
createPost,
deletePost,
getAllPosts,
getSinglePost,
updatePost
} from './controllers/routeControllers.js'
import { loggerMiddleware } from './middleware/middleware.js'
const PORT = process.env.PORT || 8000
const ID_REGEXP = /^\/api\/posts\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i
// /^\/api\/posts\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i
// /\/api\/users\/([0-9a-zA-Z-]+)/
const server = http.createServer((req, res) => {
loggerMiddleware(req, res, () => {
// GET requests for all posts
if (req.url === '/api/posts' && req.method === 'GET') {
getAllPosts(req, res)
}
// Get single post
else if (req.url.match(ID_REGEXP) && req.method === 'GET') {
const id = req.url.split('/')[3]
getSinglePost(req, res, id)
}
// Create post
else if (req.url == "/api/posts" && req.method === 'POST') {
createPost(req, res)
}
// Update post
else if (req.url.match(ID_REGEXP) && req.method === "PATCH") {
const id = req.url.split("/")[3]
updatePost(req, res, id)
}
// Delete post
else if (req.url.match(ID_REGEXP) && req.method === "DELETE") {
const id = req.url.split("/")[3]
deletePost(req, res, id)
}
else {
res.writeHead(400, 'No routes found', {
'content-type': 'application/json'
})
res.end(JSON.stringify({ message: 'No routes found!' }))
}
})
})
server.listen(PORT, () => {
log(`Server running on port ${PORT}`)
})