Last active
May 24, 2022 11:41
-
-
Save leandroandrade/64fcf3720eb6506fb29dc473ee0a3d71 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const http = require('http'); | |
const {once} = require('events'); | |
const users = [ | |
{ id: 1, name: 'John', age: 30 }, | |
{ id: 2, name: 'Paul', age: 22 }, | |
]; | |
const routes = { | |
'/users:get': (req, res) => { | |
const data = JSON.stringify({ | |
result: users, | |
}); | |
res.writeHeader(200, { | |
'Content-Type': 'application/json', | |
}); | |
res.write(`${data}\n`); | |
return res.end(); | |
}, | |
'/users:post': async (req, res) => { | |
try { | |
const [body] = await once(req, 'data'); | |
const { name, age } = JSON.parse(body) | |
const id = Math.floor(Math.random() * 100) + 1; | |
users.push({ id, name, age }); | |
res.writeHeader(201, { | |
'Content-Type': 'application/json', | |
}); | |
res.write( | |
`${JSON.stringify({ | |
message: 'Usuario criado com sucesso!', | |
})}\n` | |
); | |
return res.end(); | |
} catch (err) { | |
res.writeHeader(500, { | |
'Content-Type': 'application/json', | |
}); | |
res.write( | |
`${JSON.stringify({ | |
message: `Error: ${err.message}`, | |
})}\n` | |
); | |
return res.end(); | |
} | |
}, | |
'/users/:id:delete': (req, res) => { | |
res.writeHeader(204); | |
return res.end(); | |
}, | |
default: (req, res) => { | |
res.write('app working!\n'); | |
return res.end(); | |
}, | |
}; | |
const handler = (req, res) => { | |
const { url, method } = req; | |
const routeKey = `${url}:${method.toLowerCase()}`; | |
console.log('routeKey', routeKey); | |
const fn = routes[routeKey] || routes.default; | |
res.writeHeader(200, { | |
'Content-Type': 'text/html', | |
}); | |
return fn(req, res); | |
}; | |
http.createServer(handler).listen(3000, () => | |
console.log('Server start on port 3000') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment