forked from bradtraversy/vanilla-node-rest-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
28 lines (24 loc) · 1.13 KB
/
server.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
const http = require('http')
const { getProducts, getProduct, createProduct, updateProduct, deleteProduct } = require('./controllers/productController')
const server = http.createServer((req, res) => {
if(req.url === '/api/products' && req.method === 'GET') {
getProducts(req, res)
} else if(req.url.match(/\/api\/products\/\w+/) && req.method === 'GET') {
const id = req.url.split('/')[3]
getProduct(req, res, id)
} else if(req.url === '/api/products' && req.method === 'POST') {
createProduct(req, res)
} else if(req.url.match(/\/api\/products\/\w+/) && req.method === 'PUT') {
const id = req.url.split('/')[3]
updateProduct(req, res, id)
} else if(req.url.match(/\/api\/products\/\w+/) && req.method === 'DELETE') {
const id = req.url.split('/')[3]
deleteProduct(req, res, id)
} else {
res.writeHead(404, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ message: 'Route Not Found' }))
}
})
const PORT = process.env.PORT || 5000
server.listen(PORT, () => console.log(`Server running on port ${PORT}`))
module.exports = server;