Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bump pug-code-gen from 3.0.1 to 3.0.2 #17

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 21 additions & 11 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,24 +1,34 @@
APP_NAME=example
APP_DISPLAY_NAME=Example
APP_SECRET=RANDOMHASH
BASIC_TOKEN=8bf1a7b981d053d283d28410536a921edbeacab3

DB_HOST=mongodb://localhost/NOME DO SEU DB
DB_HOST_TEST=mongodb://localhost/NOME DO SEU DB
DB_HOST=mongodb://mongo/DBNAME
DB_HOST_TEST=mongodb://mongo/DBNAME

PORT=3000
PORT_TEST=3002
[email protected]

FB_ID=
FB_SECRET=
FB_TOKEN=
FB_PAGE=

MAIL_ACCOUNT_NAME=Example User
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USER=
MAIL_PASSWORD=
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USER=9d7293b89c9060
MAIL_PASS=bd92db7cd02553
[email protected]

EXPIRED_TOKEN_MAIL_PASSWORD=1d

PRERENDER_TOKEN=
FRONT_URL=http://localhost:8080
BACKOFFICE_URL=http://localhost
ASSETS_URL=http://localhost:3000/assets

GA_PROJECT_ID=via-varejo-analytics
GA_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC/sFqoEAaMD2fm\nkLEX4QfmVj55qve8BRRhsTkWYZBKbaafyUh48k+iY5A/28f/zy4u6DiEHCOcop73\notf1pSKdIe79/JE3BpGK60+a3u8XjLkoRY/3ZTBRGzvLsyyT1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Bc\nUEdnCujr43JcXm329ZZ0ccjOAqUZeVGY6j15CgEdFYfNEY1Amoj90MvVAoGBAIAh\nxT1xAFHAbcvMk1vpb0lHAsV2EN0oDeD5vR/apuyFdo2ySt471WnPvSgESKGzSdWC\nBVn3AKDwxHQgPQ7SlEvhbC2IveHXmN5JOTrPkM8GxhrQdTVxWhLOX7pplnjUU1hT\neIq3f3BYDlzWVpECSMsVAvYxw12pxOW6VreRBn3lAoGAclWulo0HH1FRj2t4RvjJ\nqRBAxTmCZ9bHRKDO8t8yz74z43AuDKvatzjzRL2BxNc7hyz1l1ZHbHWEHpeghbM2\nq2DkwWyYQmtlGyA8nAw1D3IHnXGAUStNh58d4r9FNKtu9mlm23Pw1TVsZjNtPSUy\nqhk07Jg8chbcoRX5NIFxuVs=\n-----END PRIVATE KEY-----\n"
GA_CLIENT_EMAIL=onboarding@via-varejo-analytics.iam.gserviceaccount.com
GA_VIEW_ID=ga:234831227

SITE_URL=http://localhost:8080
ADMIN_URL=http://localhost
ASSETS_URL=http://localhost:3000/assets
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
tmp/**/*.js
node_modules/**/*.js
jest.config.js
39 changes: 21 additions & 18 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
module.exports = {
extends: 'standard',
parserOptions: {
ecmaVersion: 2017,
sourceType: 'module'
},
rules: {
// allow paren-less arrow functions
'arrow-parens': 0,
// allow async-await
'generator-star-spacing': 0,
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
},
env: {
node: true,
mongo: true,
mocha: true
}
extends: 'standard',
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module'
},
rules: {
// allow paren-less arrow functions
'arrow-parens': 0,
// allow async-await
'generator-star-spacing': 0,
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
},
env: {
node: true,
mongo: true,
jest: true
},
globals: {
APIError: true
}
}
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,13 @@ public/files/**/*
!public/**/no_image.*
tmp/*
deploy.sh
.vscode
.idea



!.gitkeep
!**/.gitkeep

# Report coverage
teste_coverage_report
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[![Build Status](https://travis-ci.org/gfviegas/scout-cms.svg?branch=master)](https://travis-ci.org/gfviegas/express-rest-api)
[![Dependency Status](https://gemnasium.com/badges/github.com/gfviegas/express-rest-api.svg)](https://gemnasium.com/github.com/gfviegas/express-rest-api)
[![Standard - JavaScript Style Guide](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)
# API RESTful em Express, Mongoose, Mocha e Chai.
# RESTful API.

# Scripts

Expand All @@ -22,7 +22,7 @@ Os seguintes scripts estão disponiveis com `yarn run SCRIPT` ou `npm run SCRIPT
| test:unit-server | Inicia o servidor de desenvolvimento dos testes unitários, com auto-reload |
| test:report | Gera o relatório de cobertura dos testes |

# Sobre este boilerplate
# Sobre este projeto

## Organização de Pastas
Vamos seguir um padrão de organização de pastas para ficar cada coisa em seu lugar e clean.
Expand All @@ -38,6 +38,9 @@ A pasta config abriga os scripts pra inicializar o server e a conexão do mongoo
### ./actions
Sabe aquele GET `api/v1/module` que só tem a função de dar um GET da entidade e retornar? Muitas vezes você vai utilizar métodos que são idênticos em múltiplos models. É pra isso que essa folder existe. Ela abriga pequenas **ações** reaproveitáveis ao invés de poluir os controllers com códigos iguais. Utilize quantas e quais sentir necessidade, a maioria das vezes serão operações com o mongoose.

### ./models
Pasta para armazenar as models

### ./helpers
Coloque aqui os arquivos helpers, funcões modularizadas que vão facilitar a manutenção do seu código. Diferente do actions as funções aqui abrigadas não tem relação com controllers, elas podem fazer simples operações como criptografar uma string ou calcular uma média.

Expand All @@ -62,8 +65,5 @@ Para cada módulo nós vamos possuir os seguintes files:
#### controller.js
Quando cairmos nas rotas, o que a API deve fazer? Essa responsabilidade é de nosso controller, que vai utilizar actions comuns do mongoose e/ou outros métodos que você vai cadastrar nesse file.

#### model.js
Auto-explicativo. Defina aqui o schema e model do mongoose de seu module, se tiver algum.

#### validators.js
Você diversas vezes vai precisar validar parâmetros de criação e edição de dados, além de algumas lógicas customizadas (Ex: não pode possuir mais de uma moto vermelha no sistema). É aqui que você vai criar essas validações. Elas rodam no formato de middleware do express, o que significa que a sua rota só vai chegar ao controller se passar no validator cadastrado.
12 changes: 6 additions & 6 deletions tests/config/app.js → __tests__/config/app.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
const rfr = require('rfr')
const mongoose = require('mongoose')
const logger = rfr('helpers/logger')
require('./chai')()

process.env.NODE_ENV = 'test'
const app = rfr('./index')

const app = require('./server_test')

const dropDB = async () => {
if (mongoose.connection.name !== process.env.DB_HOST_TEST.split('/')[3]) {
logger.error(`[CRITICAL] - Not running in test environment DB!`)
logger.error('[CRITICAL] - Not running in test environment DB!')
logger.error(`${mongoose.connection.name} !== ${process.env.DB_HOST_TEST.split('/')[3]}`)
logger.error(`${JSON.stringify(mongoose.connection.hosts)}`)

return process.exit(1)
}

logger.info(`[INFO] - Dropping the DB...`)
logger.info('[INFO] - Dropping the DB...')
mongoose.connection.dropDatabase()
logger.info(`[INFO] - DB Dropped! \n`)
logger.info('[INFO] - DB Dropped! \n')
}

before(async () => {
beforeAll(async () => {
const res = await dropDB()
if (res) logger.info(res)
})
Expand Down
67 changes: 67 additions & 0 deletions __tests__/config/server_test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
require('dotenv').config()
const rfr = require('rfr')

rfr('/config/db')

// Import packages
const express = require('express')
const path = require('path')
const bodyParser = require('body-parser')
const busboyBodyParser = rfr('/helpers/body-parser')
const { errorHandler } = rfr('/helpers/error')
const cors = require('cors')
const validator = require('express-validator')
const timeout = require('express-timeout-handler')
const app = express()

const versions = ['v1']

rfr('/config/api_error')

global._base = path.join(__dirname, '/')

// Middlewares
app.use(timeout.handler({
timeout: 10000,
onTimeout: function (_req, res) {
res.status(503).json({ error: 'timeout' })
}
}))

if (app.get('env') === 'development') {
// app.use(logger('dev'))
app.get('/template', (req, res) => {
res.render(`${req.query.path}`, JSON.parse(req.query.data))
})
}
app.use(busboyBodyParser())
app.use(bodyParser.json({ limit: '42mb' }))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cors({
exposedHeaders: ['Content-Disposition']
}))
app.use(validator())
app.use(express.static('public'))

// Set global response headers
app.use((_req, res, next) => {
res.setHeader('Content-Type', 'application/json')
next()
})

// Apply the routes for each version setted
versions.forEach((version) => {
const versionRoutesBackoffice = rfr('/modules/backoffice/' + version + '/routes')
const versionRoutesSite = rfr('/modules/site/' + version + '/routes')
app.use('/api/' + version + '/backoffice', versionRoutesBackoffice)
app.use('/api/' + version + '/site', versionRoutesSite)
})

app.get('/', (req, res) => {
res.status(200).json({ messsage: 'test ok' })
})

// Global error handler
app.use(errorHandler)

module.exports = app
23 changes: 23 additions & 0 deletions __tests__/helpers/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// const rfr = require('rfr')
// const jwtHelper = rfr('helpers/jwt')

// module.exports = (Model) => {
// const helper = {}

// helper.getAuthorizedUser = (query) => {
// return Model.findOne(query)
// }

// helper.getJWTFromUser = (user) => {
// return jwtHelper.generateToken(user)
// }

// helper.getJWTFromUserQuery = (query) => {
// return async (resolve, _reject) => {
// const user = await helper.getAuthorizedUser(query)
// return resolve(jwtHelper.generateToken(user))
// }
// }

// return helper
// }
65 changes: 65 additions & 0 deletions __tests__/helpers/request.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@

// const req = {
// checkParams: () => { },
// checkBody: () => { },
// notEmpty: () => { },
// len: () => { },
// isEmail: () => { },
// isMongoId: () => { },
// isBoolean: () => { },
// matches: () => { },
// isIn: () => { },
// getValidationResult: () => { }
// }
// const checkBody = (req) => { return sinon.stub(req, 'checkBody').returnsThis() }
// const checkParams = (req) => { return sinon.stub(req, 'checkParams').returnsThis() }
// const notEmpty = (req) => { return sinon.stub(req, 'notEmpty').returnsThis() }
// const len = (req) => { return sinon.stub(req, 'len').returnsThis() }
// const isEmail = (req) => { return sinon.stub(req, 'isEmail').returnsThis() }
// const isIn = (req) => { return sinon.stub(req, 'isIn').returnsThis() }
// const isMongoId = (req) => { return sinon.stub(req, 'isMongoId').returnsThis() }
// const isBoolean = (req) => { return sinon.stub(req, 'isBoolean').returnsThis() }
// const matches = (req) => { return sinon.stub(req, 'matches').returnsThis() }
// const getValidationResult = (req) => {
// return sinon.stub(req, 'getValidationResult').callsFake(() => {
// return new Promise((resolve, reject) => {
// resolve({
// array: () => {
// return []
// },
// mapped: () => {
// return []
// },
// isEmpty: () => {
// return true
// },
// next: () => { }
// })
// })
// })
// }

// const res = {
// status: () => { },
// json: () => { }
// }
// const status = sinon.stub(res, 'status').returnsThis()
// const json = sinon.stub(res, 'json').returnsThis()

// module.exports = {
// stubReq: () => { return req },
// stubCheckBody: (req) => { return checkBody(req) },
// stubCheckParams: (req) => { return checkParams(req) },
// stubNotEmpty: (req) => { return notEmpty(req) },
// stubLen: (req) => { return len(req) },
// stubIsEmail: (req) => { return isEmail(req) },
// stubIsMongoId: (req) => { return isMongoId(req) },
// stubIsBoolean: (req) => { return isBoolean(req) },
// stubMatches: (req) => { return matches(req) },
// stubIsIn: (req) => { return isIn(req) },
// stubGetValidationResult: (req) => { return getValidationResult(req) },

// stubRes: (req) => { return res(req) },
// stubStatus: (req) => { return status(req) },
// stubJson: (req) => { return json(req) }
// }
28 changes: 28 additions & 0 deletions __tests__/helpers/routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// module.exports = (routes) => {
// const registredRoutes = {
// head: [],
// get: [],
// post: [],
// put: [],
// patch: [],
// delete: []
// }

// routes.stack.forEach((r) => {
// if (r.route && r.route.path) {
// const routeMethods = Object.keys(r.route.methods)
// routeMethods.forEach((method) => {
// registredRoutes[method].push(r.route.path)
// })
// }
// })

// return {
// getRoutes: () => {
// return registredRoutes
// },
// checkRoute: (method, path) => {
// return !!(registredRoutes[method].indexOf(path) > -1)
// }
// }
// }
Loading