Skip to content

Commit

Permalink
Merge pull request #33 from servirme/generic-improvements
Browse files Browse the repository at this point in the history
Generic small improvements
  • Loading branch information
matheusvellone committed Oct 29, 2018
2 parents 1b9bef1 + 1d19289 commit ee08a17
Show file tree
Hide file tree
Showing 27 changed files with 71 additions and 99 deletions.
12 changes: 0 additions & 12 deletions config/app.js

This file was deleted.

2 changes: 0 additions & 2 deletions config/environment/test
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
NODE_ENV=test

DATABASE_LOGGING=true

DATABASE_HOST=postgres
DATABASE_DATABASE=servirme
DATABASE_USERNAME=postgres
Expand Down
5 changes: 3 additions & 2 deletions config/errorCodes.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ module.exports = {
validationError: 1000,
notFound: {
generic: 1100,
user: 1101,
establishment: 1102,
url: 1101,
user: 1102,
establishment: 1103,
},
conflict: {
generic: 1200,
Expand Down
7 changes: 7 additions & 0 deletions config/i18n.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
default: 'en-US',
locales: [
'pt-BR',
'en-US',
],
}
2 changes: 1 addition & 1 deletion nodemon.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"verbose": true,
"verbose": false,
"ignore": [
"logs/*"
],
Expand Down
12 changes: 5 additions & 7 deletions src/app.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
require('./global-setup')
require('./setup')
const express = require('express')
const cors = require('cors')
const { json } = require('body-parser')
Expand All @@ -12,6 +12,7 @@ const {
const { wrapAction } = require('./helpers/express')
const appGenericRoutes = require('./routes/otherRoutes')
const appRoutes = require('./routes/appRoutes')
const NotFoundError = require('./Errors/NotFound')

const app = express()

Expand All @@ -27,12 +28,9 @@ app.use(requestMetadata)
app.use(appGenericRoutes)
app.use(appRoutes)

const notFoundResponse = () => ({
statusCode: 404,
body: {
message: 'url-not-found',
},
})
const notFoundResponse = () => {
throw new NotFoundError('url')
}

app.all('*', wrapAction(notFoundResponse))

Expand Down
3 changes: 2 additions & 1 deletion src/bin/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ if (!validEnvs.includes(env)) {

sequelize.authenticate()
.then(() => {
logger.debug('Successfully connected to database')
app.listen(PORT, () => {
logger.info(`Server is running in '${env}' mode on port ${PORT}`)
logger.debug(`Server is running in '${env}' mode on port ${PORT}`)
})
})
1 change: 0 additions & 1 deletion config/constants.js → src/constants.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
module.exports = {
CDN_BASE: 'https://cdn.servir.me',
AUTH: {
HEADER: 'token',
LEVELS: {
Expand Down
10 changes: 2 additions & 8 deletions src/controllers/establishment.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@ const establishmentModel = require('../models/establishment')
module.exports.create = async ({ body, auth }) => {
const { id: userId } = auth.user

const establishment = await establishmentModel.createEstablishment(
body,
userId
)
const establishment = await establishmentModel.createEstablishment(body, userId)

return {
statusCode: 201,
Expand All @@ -18,10 +15,7 @@ module.exports.create = async ({ body, auth }) => {
}

module.exports.update = async ({ body, params }) => {
const establishment = await establishmentModel.updateEstablishment(
params.id,
body
)
const establishment = await establishmentModel.updateEstablishment(params.id, body)

return {
statusCode: 200,
Expand Down
13 changes: 4 additions & 9 deletions src/database.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,23 @@
const Sequelize = require('sequelize')
const log4js = require('log4js')

const { isProd } = require('../config/env')

const {
DATABASE_DATABASE,
DATABASE_DIALECT,
DATABASE_HOST,
DATABASE_PASSWORD,
DATABASE_USERNAME,
DATABASE_LOGGING,
} = process.env
const logger = log4js.getLogger('database')

const logging = (isProd || DATABASE_LOGGING === 'true') && logger.debug.bind(logger)
const operators = Sequelize.Op

const sequelizeConfig = {
database: DATABASE_DATABASE,
host: DATABASE_HOST,
dialect: DATABASE_DIALECT,
logging,
operatorsAliases: Sequelize.Op,
logging: false,
operatorsAliases: operators,
username: DATABASE_USERNAME,
password: DATABASE_PASSWORD,
benchmark: true,
pool: {
handleDisconnects: true,
idle: 60000,
Expand All @@ -37,3 +31,4 @@ const sequelizeConfig = {
const sequelize = new Sequelize(sequelizeConfig)

module.exports = sequelize
module.exports.Operators = operators
13 changes: 8 additions & 5 deletions src/helpers/I18n/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
const { join } = require('path')
const i18n = require('i18n')
const log4js = require('log4js')
const { i18n: i18nConfig } = require('../../../config/app')
const { assoc } = require('ramda')

const i18nConfig = require('../../../config/i18n')

const logger = log4js.getLogger('api')

Expand Down Expand Up @@ -33,16 +35,17 @@ module.exports.getInstance = (language) => {
const translated = this.__(key, data)

if (translated === key) {
logger.warn(`Response not translated: '${key}'`)
logger.warn({
message: 'Response not translated',
key,
})
}

return translated
},
}

const i18nInstanceConfig = Object.assign(i18nBaseConfig, {
register: instance,
})
const i18nInstanceConfig = assoc('register', instance, i18nBaseConfig)
i18n.configure(i18nInstanceConfig)
instance.setLocale(language)

Expand Down
4 changes: 2 additions & 2 deletions src/helpers/I18n/locales/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
"body": "invalid.body",
"jwt": "invalid.jwt"
},
"url-not-found": "url-not-found",
"plans": {
"list": "Listing all plans successfully",
"show": "Listing plan details successfully"
Expand All @@ -53,7 +52,8 @@
},
"not-found": {
"user": "not-found.user",
"establishment": "not-found.establishment"
"establishment": "not-found.establishment",
"url": "not-found.url"
},
"conflict": {
"user": "conflict.user",
Expand Down
4 changes: 2 additions & 2 deletions src/helpers/I18n/locales/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
"body": "invalid.body",
"jwt": "invalid.jwt"
},
"url-not-found": "url-not-found",
"status": {
"ok": "OK",
"okaaaa": "status.okaaaa"
Expand All @@ -44,7 +43,8 @@
},
"not-found": {
"user": "not-found.user",
"establishment": "not-found.establishment"
"establishment": "not-found.establishment",
"url": "not-found.url"
},
"conflict": {
"user": "conflict.user",
Expand Down
3 changes: 1 addition & 2 deletions src/helpers/database.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
const Sequelize = require('sequelize')
const { merge } = require('ramda')

const sequelize = require('../database')
Expand All @@ -19,6 +18,6 @@ const paginate = (
return model.findAll(databaseOptions)
}

module.exports.Op = Sequelize.Op
module.exports.Operators = sequelize.Operators
module.exports.getTransaction = getTransaction
module.exports.paginate = paginate
21 changes: 14 additions & 7 deletions src/helpers/express.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,25 @@ const {
module.exports.wrapAction = action => async (req, res, next) => {
try {
const response = await action(req)

if (!response.statusCode) {
throw new Error('Missing statusCode in response')
}

const {
statusCode = 200,
statusCode,
body = {},
headers = {},
translate = [],
} = response

translate.forEach(res.translate)
if (response.translate) {
response.translate.forEach(res.translate)
}

forEach(([key, value]) => {
res.set(key, value)
}, toPairs(headers))
if (response.headers) {
forEach(([key, value]) => {
res.set(key, value)
}, toPairs(response.headers))
}

// NOTE: will log body before applying i18n middleware
res.body = body
Expand Down
2 changes: 1 addition & 1 deletion src/middlewares/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const { path } = require('ramda')
const jwt = require('../helpers/jwt')
const NotAuthorizedError = require('../Errors/NotAuthorized')
const ForbiddenError = require('../Errors/Forbidden')
const { AUTH } = require('../../config/constants')
const { AUTH } = require('../constants')
const { jwt: jwtValidator } = require('../validators/auth')

const { HEADER, LEVELS } = AUTH
Expand Down
2 changes: 1 addition & 1 deletion src/models/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const userTransform = require('../transforms/user')
const InvalidError = require('../Errors/Invalid')
const { checkHashPassword } = require('../helpers/security')
const { sign } = require('../helpers/jwt')
const { AUTH } = require('../../config/constants')
const { AUTH } = require('../constants')

const signJwtUser = user => sign({ type: AUTH.LEVELS.ADMIN, user })
const checkPassword = async (plainTextPassword, user) => {
Expand Down
4 changes: 2 additions & 2 deletions src/models/user.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const { pluck } = require('ramda')

const establishmentTransform = require('../transforms/establishment')
const { models, Op } = require('./database')
const { models, Operators } = require('./database')
const { hashPassword } = require('../helpers/security')
const { checkConflict, checkExists } = require('../helpers/model')

Expand Down Expand Up @@ -33,7 +33,7 @@ module.exports.getEstablishments = async (userId) => {
const establishmentIds = pluck('establishment_id', userEstablishments)

const establishments = await models.Establishment.findAll({
where: { id: { [Op.in]: establishmentIds } },
where: { id: { [Operators.in]: establishmentIds } },
})

const transformedEstablishments = establishments
Expand Down
6 changes: 0 additions & 6 deletions src/routes/establishment.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ const {
show,
create,
update,
// userEstabilishments,
} = require('../controllers/establishment')
const {
adminAuth,
Expand All @@ -25,11 +24,6 @@ router.post(
validate(createSchema),
wrapAction(create)
)
// router.get(
// '/establishments/my',
// adminAuth,
// wrapAction(userEstabilishments)
// )
router.put(
'/establishment/:id',
adminAuth,
Expand Down
3 changes: 1 addition & 2 deletions src/routes/otherRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ const status = () => {
return {
statusCode: 200,
body: {
date: now.toISOString(),
timestamp: now.getTime(),
datetime: now.toISOString(),
message: 'status.ok',
},
}
Expand Down
2 changes: 0 additions & 2 deletions src/global-setup.js → src/setup/global.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
const BbPromise = require('bluebird')

require('../config/logger')

global.Promise = BbPromise
2 changes: 2 additions & 0 deletions src/setup/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
require('./global')
require('./logger')

0 comments on commit ee08a17

Please sign in to comment.