Skip to content

Commit

Permalink
Merge pull request zanfranceschi#8 from lucashmsilva/tira_express
Browse files Browse the repository at this point in the history
tira pacotes express e body-parser
  • Loading branch information
bermr authored Feb 19, 2024
2 parents 5d6fa54 + 9d4c7ec commit 009d02a
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 34 deletions.
4 changes: 2 additions & 2 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
- Validar keepalive?
- Remover retorno de JSON dos caso de erro ✅
- Node clusters
- Remover body (retornar head)
- body parser?
- Remover body (retornar head)
- Tirar express body parser?
- readme
- organizar o código
2 changes: 1 addition & 1 deletion nginx.conf
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
events {
worker_connections 256;
worker_connections 400;
}

http {
Expand Down
4 changes: 1 addition & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,9 @@
"author": "lucashmsilva",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.2",
"express": "^4.18.2",
"postgres": "^3.4.3"
},
"devDependencies": {
"nodemon": "^3.0.3"
}
}
}
62 changes: 34 additions & 28 deletions src/app.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
const express = require('express');
const bodyParser = require('body-parser');
const { createServer } = require('node:http');
const postgres = require('postgres');

const getExtrato = require('./extrato-get');
const createTransacao = require('./trasacoes-create');

let sql;
async function setupDbConnection() {
const dbUser = process.env.DB_USER;
const dbPassword = process.env.DB_PASSWORD;
const dbName = process.env.DB_NAME;
const dbMaxPoolSize = process.env.DB_MAX_POOL_SIZE;
const dbInitialPoolSize = process.env.DB_INITIAL_POOL_SIZE;

const sql = postgres({
sql = postgres({
host: 'db',
port: 5432,
database: dbName,
Expand All @@ -26,55 +26,61 @@ async function setupDbConnection() {
poolWarmup.push(sql`SELECT 1+1`);
}
await Promise.all([poolWarmup]);

return sql;
}

function setupApp(sql) {
const app = express();
app.use(bodyParser.json());
async function handleRequest(req, res) {
const { method, url } = req;

app.post('/clientes/:id/transacoes', async (req, res) => {
try {
const clientId = +req.params.id;
const { valor, tipo, descricao } = req.body;
const urlString = url.split('/');
const clientId = +urlString[2];
const pathname = urlString[3];

const response = await createTransacao.run(sql, { clientId, valor, tipo, descricao });
if (clientId > 5) {
return res.writeHead(404).end();
}

return res.status(200).json(response);
if (method === 'POST' && pathname === 'transacoes') {
try {
let body = '';
for await (const chunk of req) body += chunk;

const { valor, tipo, descricao } = JSON.parse(body);
const response = await createTransacao.run(sql, { clientId, valor: +valor, tipo, descricao });
return res.writeHead(200, { 'Content-type': 'application/json' }).end(JSON.stringify(response))
} catch (err) {
if (err.message === 'client_not_found') {
return res.status(404).end();
return res.writeHead(404).end();
}

if (err.message === 'insufficient_limit') {
return res.writeHead(422).end();
}

return res.status(422).end();
return res.writeHead(422).end();
}
});
}

app.get('/clientes/:id/extrato', async (req, res) => {
if (method === 'GET' && pathname === 'extrato') {
try {
const clientId = +req.params.id;

const response = await getExtrato.run(sql, { clientId });

return res.json(response).status(200).end();
return res.writeHead(200, { 'Content-type': 'application/json' }).end(JSON.stringify(response))
} catch (err) {
if (err.message === 'client_not_found') {
return res.status(404).end();
return res.writeHead(404).end();
}

return res.status(500).end();
return res.writeHead(500).end();
}
});
}

return app;
return res.writeHead(404).end();
}

async function init() {
const port = process.env.PORT;

const dbConnection = await setupDbConnection();
const server = setupApp(dbConnection);
await setupDbConnection();
const server = createServer(handleRequest);

server.listen(port, () => {
console.log(`Server started on port ${port}`);
Expand Down

0 comments on commit 009d02a

Please sign in to comment.