Skip to content

Commit

Permalink
feat: ✨ Inclusao da classe ApiResponse para retorno de respostas
Browse files Browse the repository at this point in the history
Padronizacao das mensagens e status de erro e criacao do model ApiResponse
  • Loading branch information
LucasTonetto committed May 28, 2021
1 parent c2b7af5 commit 9d66427
Show file tree
Hide file tree
Showing 20 changed files with 438 additions and 143 deletions.
20 changes: 16 additions & 4 deletions dist/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ const fileUpload = require('express-fileupload');
const routes_1 = require('./routes/routes');
const dotenv_1 = require('dotenv');
const AuthDAO_1 = require('./models/DAO/AuthDAO');
const ApiResponse_1 = require('./models/ApiResponse');
dotenv_1.config({ path: __dirname + '/../.env' });
const app = express();
app.use(
Expand All @@ -63,13 +64,14 @@ app.use(
],
exposedHeaders: ['token', 'agency', 'company', 'campaign', 'file', 'data', 'config', 'permission', 'email'],
origin: '*',
methods: 'GET,POST',
methods: 'GET, POST',
preflightContinue: false,
})
);
app.all('*', (req, res, next) =>
__awaiter(void 0, void 0, void 0, function* () {
const token = req.headers.token;
const apiResponse = new ApiResponse_1.ApiResponse();
if (token) {
const authDAO = new AuthDAO_1.AuthDAO(token);
authDAO
Expand All @@ -80,14 +82,24 @@ app.all('*', (req, res, next) =>
if (auth.hasPermissionFor(req.url, req.method)) {
next();
} else {
res.status(403).send('Usuário sem permissão para realizar a ação!');
apiResponse.responseText = 'Usuário sem permissão para realizar a ação!';
apiResponse.statusCode = 403;
}
})
.catch((err) => {
res.status(403).send('Usuário Inválido');
apiResponse.responseText = 'Usuário Inválido!';
apiResponse.statusCode = 401;
apiResponse.errorMessage = err.message;
})
.finally(() => {
if (apiResponse.statusCode !== 200) {
res.status(apiResponse.statusCode).send(apiResponse.jsonResponse);
}
});
} else {
res.status(403).send('Token não informado!');
apiResponse.responseText = 'Token não informado!';
apiResponse.statusCode = 401;
res.status(apiResponse.statusCode).send(apiResponse.jsonResponse);
}
})
);
Expand Down
32 changes: 32 additions & 0 deletions dist/models/ApiResponse.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.ApiResponse = void 0;
class ApiResponse {
constructor(statusCode = 200, responseText = '', errorMessage = '') {
this._statusCode = statusCode;
this._responseText = responseText;
this._errorMessage = errorMessage;
}
set statusCode(statusCode) {
this._statusCode = statusCode;
}
set responseText(responseText) {
this._responseText = responseText;
}
set errorMessage(errorMessage) {
this._errorMessage = errorMessage;
}
get statusCode() {
return this._statusCode;
}
get responseText() {
return this._responseText;
}
get jsonResponse() {
return {
responseText: this._responseText,
errorMessage: this._errorMessage,
};
}
}
exports.ApiResponse = ApiResponse;
4 changes: 3 additions & 1 deletion dist/models/DAO/AuthDAO.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ class AuthDAO {
const jsonAuth = data.data();
return new Auth_1.Auth(jsonAuth.permission, jsonAuth.company, jsonAuth.agency, jsonAuth.email);
})
.catch((err) => console.log(err));
.catch((err) => {
throw err;
});
}
addAuth(auth) {
return this._objectStore
Expand Down
9 changes: 7 additions & 2 deletions dist/models/DAO/ConfigDAO.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,19 @@ class ConfigDAO {
return this._objectStore
.getAllDocumentsFrom(this._configCollection)
.then((documents) => {
if (documents.length === 0) {
throw new Error('A empresa não possui nenhuma configuração!');
}
let lastDocument;
documents.forEach((doc, index) => {
if (index === 0) lastDocument = doc;
if (doc.version > lastDocument.version) lastDocument = doc;
});
return new Config_1.Config(lastDocument);
})
.catch((err) => console.log(err));
.catch((err) => {
throw new Error(err.message);
});
}
addConfig(config) {
return new Promise((resolve, reject) => {
Expand All @@ -37,7 +42,7 @@ class ConfigDAO {
this._objectStore.addDocumentIn(this._configCollection, config.toJson(), `config_${config.version}`)
);
} else {
reject('Configuração inválida');
throw new Error('Configuração inválida!');
}
})
.catch((err) => reject(err));
Expand Down
46 changes: 29 additions & 17 deletions dist/routes/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,25 @@ const FileDAO_1 = require('../models/DAO/FileDAO');
const DateUtils_1 = require('../utils/DateUtils');
const CsvUtils_1 = require('../utils/CsvUtils');
const Builder_1 = require('../controllers/Builder');
const ApiResponse_1 = require('../models/ApiResponse');
const converter = require('json-2-csv');
const build = (app) => {
app.post('/build/:media', (req, res) => {
const media = req.params.media;
const company = req.company;
const agency = req.agency;
const campaign = req.headers.campaign;
if (!req.files.data) {
res.status(400).send({
message: 'Nenhum arquivo foi enviado!',
});
const apiResponse = new ApiResponse_1.ApiResponse();
if (!req.files || !req.files.data) {
apiResponse.responseText = 'Nenhum arquivo foi enviado!';
apiResponse.statusCode = 400;
res.status(apiResponse.statusCode).send(apiResponse.jsonResponse);
return;
} else if (!campaign) {
res.status(400).send({
message: 'Nenhuma campanha foi informada!',
});
apiResponse.responseText = 'Nenhuma campanha foi informada!';
apiResponse.statusCode = 400;
res.status(apiResponse.statusCode).send(apiResponse.jsonResponse);
return;
}
const fileContent = req.files.data.data;
const filePath = agency
Expand All @@ -31,20 +34,18 @@ const build = (app) => {
configDAO
.getLastConfig()
.then((config) => {
if (config) {
companyConfig = config;
companyConfig = config;
if (companyConfig) {
if (!companyConfig.toJson()[media]) {
res.status(400).send({
message: `Mídia ${media} não configurada!`,
});
return;
apiResponse.statusCode = 400;
throw new Error(`Mídia ${media} não foi configurada!`);
}
const fileDAO = new FileDAO_1.FileDAO();
fileDAO.file = fileContent;
return fileDAO.save(filePath);
} else {
res.status(400).send('Nenhuma configuração encontrada!');
return;
apiResponse.statusCode = 500;
throw new Error('Nenhuma configuração encontrada!');
}
})
.then(() => {
Expand All @@ -63,7 +64,9 @@ const build = (app) => {
csv += '\nConfiguracao inserida em;' + configTimestamp;
res.setHeader('Content-disposition', 'attachment; filename=data.csv');
res.set('Content-Type', 'text/csv; charset=utf-8');
res.status(200).send(csv);
apiResponse.responseText = csv;
apiResponse.statusCode = 200;
res.status(apiResponse.statusCode).send(apiResponse.responseText);
},
{
delimiter: {
Expand All @@ -73,7 +76,16 @@ const build = (app) => {
);
})
.catch((err) => {
res.status(500).send('Falha ao salvar arquivo!');
if (apiResponse.statusCode === 200) {
apiResponse.statusCode = 500;
}
apiResponse.responseText = 'Falha ao salvar o arquivo!';
apiResponse.errorMessage = err.message;
})
.finally(() => {
if (apiResponse.statusCode !== 200) {
res.status(apiResponse.statusCode).send(apiResponse.jsonResponse);
}
});
});
};
Expand Down
31 changes: 22 additions & 9 deletions dist/routes/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,39 +2,52 @@
Object.defineProperty(exports, '__esModule', { value: true });
const ConfigDAO_1 = require('../models/DAO/ConfigDAO');
const Config_1 = require('../models/Config');
const ApiResponse_1 = require('../models/ApiResponse');
const config = (app) => {
app.post('/config', (req, res) => {
const company = req.company;
const configString = req.body.config;
const apiResponse = new ApiResponse_1.ApiResponse();
if (!configString) {
res.status(400).send('Configuração não foi informada!');
apiResponse.responseText = 'Configuração não foi informada!';
apiResponse.statusCode = 400;
res.status(apiResponse.statusCode).send(apiResponse.jsonResponse);
return;
}
const config = new Config_1.Config(JSON.parse(configString));
const configDAO = new ConfigDAO_1.ConfigDAO(company);
configDAO
.addConfig(config)
.then((data) => {
res.status(200).send('Configuração criada com sucesso!');
apiResponse.responseText = 'Configuração criada com sucesso!';
apiResponse.statusCode = 200;
})
.catch((err) => {
res.status(500).send('Erro ao criar a configuração!');
apiResponse.responseText = 'Erro ao criar a configuração!';
apiResponse.statusCode = 500;
apiResponse.errorMessage = err.message;
})
.finally(() => {
res.status(apiResponse.statusCode).send(apiResponse.jsonResponse);
});
});
app.get('/config', (req, res) => {
const company = req.company;
const configDAO = new ConfigDAO_1.ConfigDAO(company);
const apiResponse = new ApiResponse_1.ApiResponse();
configDAO
.getLastConfig()
.then((config) => {
if (config) {
res.status(200).send(config.toString());
} else {
res.status(200).send('{}');
}
apiResponse.responseText = config.toString();
apiResponse.statusCode = 200;
})
.catch((err) => {
res.status(500).send('Erro ao recuperar configuração!');
apiResponse.statusCode = 500;
apiResponse.responseText = 'Erro ao recuperar configuração!';
apiResponse.errorMessage = err.message;
})
.finally(() => {
res.status(apiResponse.statusCode).send(apiResponse.jsonResponse);
});
});
};
Expand Down
Loading

0 comments on commit 9d66427

Please sign in to comment.