serverest 2.24.2 → 2.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,116 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.25.1](https://github.com/ServeRest/ServeRest/compare/v2.25.0...v2.25.1) (2021-11-23)
4
+
5
+
6
+ ### Chores
7
+
8
+ * **patch:** desabilitar monitoramento enquanto ajusto rate limit ([fb5098b](https://github.com/ServeRest/ServeRest/commit/fb5098bea9253e7606d8d5c66f252bf9a6870a3c))
9
+
10
+
11
+ ### Continuous Integration
12
+
13
+ * **environment:** limit prod secrets to trunk and beta branch ([56fb980](https://github.com/ServeRest/ServeRest/commit/56fb980d9d6add7cc92e96277421ff3a1db3a2c2))
14
+
15
+
16
+ ### Documentation
17
+
18
+ * **readme:** include playwright automation repo ([492400c](https://github.com/ServeRest/ServeRest/commit/492400c6bbdf3ce48b092e38c1eadc6ac8a0e410))
19
+
20
+ # [2.25.0](https://github.com/ServeRest/ServeRest/compare/v2.24.4...v2.25.0) (2021-11-22)
21
+
22
+
23
+ ### Chores
24
+
25
+ * criar multi-stage build para execução do projeto com nodemon ([9b8bca5](https://github.com/ServeRest/ServeRest/commit/9b8bca520a67eeaa0d08b3f1323a4cc515d38dd3))
26
+ * **docker:** avoid using 'prepare' on prod image ([bc4a9c7](https://github.com/ServeRest/ServeRest/commit/bc4a9c710fe7a91f27bd991dcfd31a260cbad6c8))
27
+ * **dockerfile:** incluir labels com informações do projeto ([7cbdd6c](https://github.com/ServeRest/ServeRest/commit/7cbdd6c0c60a7907941d1fd5dd2ea30a6d823f17))
28
+ * generate package-lock with newer version of npm ([e7b28a0](https://github.com/ServeRest/ServeRest/commit/e7b28a028c6d9ac547e58c4f12774a211578655a))
29
+ * guarantee that pipeline will break when test fail ([22a9629](https://github.com/ServeRest/ServeRest/commit/22a962982096b40fb7420beca3241161b7aa7f4c))
30
+ * **infra-test:** containerize infra test to easier run ([ad9529d](https://github.com/ServeRest/ServeRest/commit/ad9529dfeda47eacf487b947eec6b4bec7d28fe1))
31
+ * renomear test de api para teste de integração ([1368f38](https://github.com/ServeRest/ServeRest/commit/1368f38c186212d2307884dc0ee434c5ae8996a1))
32
+ * set specific version of base images ([ca4c152](https://github.com/ServeRest/ServeRest/commit/ca4c152ae3174376912977ade20119047f60b8fc))
33
+ * **sonar:** remover análise de coverage de arquivos que não necessitam ter testes ([9f5ae1f](https://github.com/ServeRest/ServeRest/commit/9f5ae1f3e28d71d860b8a58d68b4c3a030cde83b))
34
+ * **test:** exibir cor na execução de teste de integração para facilitar leitura ([44ef82d](https://github.com/ServeRest/ServeRest/commit/44ef82d6e2ea4a1f130d767f40e0341a8489a256))
35
+
36
+
37
+ ### Continuous Integration
38
+
39
+ * explicitar o nome da imagem docker ([a2eb8c2](https://github.com/ServeRest/ServeRest/commit/a2eb8c238e55acffc7de3b5149120b2627505090))
40
+ * remover execução de teste que não está containerizado ([123eb10](https://github.com/ServeRest/ServeRest/commit/123eb106101bc56201e188c3a925182fce0dc7e1))
41
+
42
+
43
+ ### Documentation
44
+
45
+ * **contributing:** detalhar a seção de testes com os pacotes utilizados e informação de coverage ([687395e](https://github.com/ServeRest/ServeRest/commit/687395e6e145384c4ac93af096b95bc01f480f2e))
46
+ * **readme:** adicionar repositório de automação em ruby ([bd828af](https://github.com/ServeRest/ServeRest/commit/bd828af2b993e3ef4558e130ed5252a287d52c9c))
47
+
48
+
49
+ ### Features
50
+
51
+ * **rate-limit:** interceptar requests de testes de carga para não enviar os dados para o moesif ([7683cd0](https://github.com/ServeRest/ServeRest/commit/7683cd0060b3312c17305496d580729f3a71a687))
52
+
53
+
54
+ ### Tests
55
+
56
+ * fix infra test error ([6345210](https://github.com/ServeRest/ServeRest/commit/634521029dadc92ba3e0b52775b008c7c80bf37f))
57
+ * **infra:** avoid test caching ([befbf6e](https://github.com/ServeRest/ServeRest/commit/befbf6e7d7318964d86f94cb4f12dcdb9b3ff407))
58
+ * **unitario:** garantir comportamento do método getRandomFinancialContributor ([d4debd7](https://github.com/ServeRest/ServeRest/commit/d4debd7691255e307dcef61c986d7486cfc51d30))
59
+ * utilizar multi-stage build ([ed69b62](https://github.com/ServeRest/ServeRest/commit/ed69b6269178ec13382f643a22226fc4dcfe2fe4))
60
+
61
+ ## [2.24.4](https://github.com/ServeRest/ServeRest/compare/v2.24.3...v2.24.4) (2021-10-13)
62
+
63
+
64
+ ### Chores
65
+
66
+ * **makefile:** executar as imagens utilizando 'docker-compose up' ao invés de run ([d8f3885](https://github.com/ServeRest/ServeRest/commit/d8f3885f6ec9c5d43ca51ddd32f46c6a42940991))
67
+ * bump stryker-mutator and stryker-diff-runner to latest ([e9fa90d](https://github.com/ServeRest/ServeRest/commit/e9fa90d5d04f70ecb07d08142b6e48fa02a747ed))
68
+
69
+
70
+ ### Code Refactoring
71
+
72
+ * **database:** alterar o banco de dados para um fork atualizado e com promise implementado ([ee2eca3](https://github.com/ServeRest/ServeRest/commit/ee2eca33ee38b4b51f32c0b9d88876bf0a761ce7))
73
+
74
+
75
+ ### Continuous Integration
76
+
77
+ * executar webhook encima de commit deployado ([da7c099](https://github.com/ServeRest/ServeRest/commit/da7c099b42e79e033e823b230e58d928386b1df5))
78
+ * fixar versão do semantic-release ([bc37107](https://github.com/ServeRest/ServeRest/commit/bc37107683771ca4e0103f35bef2908f2e9b9a4f))
79
+
80
+
81
+ ### Documentation
82
+
83
+ * **patch:** detalhar sobre como usar para teste de carga ([c676d7a](https://github.com/ServeRest/ServeRest/commit/c676d7acd96f4d5d4c0d70479aef9cd455beb862))
84
+
85
+ ## [2.24.3](https://github.com/ServeRest/ServeRest/compare/v2.24.2...v2.24.3) (2021-08-07)
86
+
87
+
88
+ ### Chores
89
+
90
+ * **patch:** exibir nome de apoiador financeiro de forma randômica no terminal em agradecimento ([0cdf51a](https://github.com/ServeRest/ServeRest/commit/0cdf51a17df5e6424be108cc5e045dc4ad19b8aa))
91
+ * **sonar:** remove scan fron server.js ([6ab2188](https://github.com/ServeRest/ServeRest/commit/6ab21880267a18fab341e04b1c5e27f727bc262c))
92
+ * containerize contract test ([70f596b](https://github.com/ServeRest/ServeRest/commit/70f596b22acd64d56bfda59a3eeb862944fd81a4))
93
+ * containerize integration test ([003951d](https://github.com/ServeRest/ServeRest/commit/003951d88a387b170c1f27966890787c970136db))
94
+ * containerize mutation test ([7448051](https://github.com/ServeRest/ServeRest/commit/74480512a65f70b616829fafba9ebacf4d5e136c))
95
+ * containerize mutation test diff ([6adee62](https://github.com/ServeRest/ServeRest/commit/6adee62563d1a0a17415a1b5e55184b0a128f4e8))
96
+ * create docker-compose base ([d7089e9](https://github.com/ServeRest/ServeRest/commit/d7089e91c58c3d57ff343d9809809d881400d77a))
97
+
98
+
99
+ ### Continuous Integration
100
+
101
+ * **test-contract:** remove unused env variable ([69337d0](https://github.com/ServeRest/ServeRest/commit/69337d0208573e557ac983ef4b323926c6725a09))
102
+ * remove global environment ([f400b89](https://github.com/ServeRest/ServeRest/commit/f400b8918801483a42a57c02d5ff2f36a2e0423e))
103
+
104
+
105
+ ### Documentation
106
+
107
+ * **contributing:** update with info about 'make' ([eef85c9](https://github.com/ServeRest/ServeRest/commit/eef85c9ef2fb73346a34a583248bc951c14c118b))
108
+
109
+
110
+ ### Tests
111
+
112
+ * **contract:** refatorar o teste para permitir alteração de contrato ([286a413](https://github.com/ServeRest/ServeRest/commit/286a413f0bb8d62ca20bcfbd84354577fea74b83))
113
+
3
114
  ## [2.24.2](https://github.com/ServeRest/ServeRest/compare/v2.24.1...v2.24.2) (2021-05-18)
4
115
 
5
116
 
package/README.md CHANGED
@@ -25,6 +25,7 @@
25
25
 
26
26
  _ServeRest_ permite o estudo de:
27
27
  - Verbos *GET, POST, PUT* e *DELETE* com persistência de dados
28
+ - [Teste de carga](https://github.com/ServeRest/ServeRest#teste-de-carga)
28
29
  - Autenticação no header
29
30
  - Query string
30
31
  - Teste de schema json
@@ -126,20 +127,39 @@ Em ambos os comandos de subida de ambiente local será utilizado a última vers
126
127
 
127
128
  Você pode encontrar as versões disponíveis na [lista de tags no Docker Hub](https://hub.docker.com/r/paulogoncalvesbh/serverest/tags) e na [lista de versões do NPM](https://www.npmjs.com/package/serverest).
128
129
 
130
+ ## Teste de carga
131
+
132
+ Para acompanhar o comportamento do ambiente aonde o ServeRest está hospedado você pode acessar a página https://serverest.dev/status, pois contém informações como:
133
+
134
+ - Uso de CPU.
135
+ - Uso da memória.
136
+ - Tempo de resposta.
137
+ - RPS (Requisições por segundo).
138
+
139
+ > Fez teste de carga? O que acha de compartilhar com o autor do projeto o relatório final contendo dados de RPS para auxiliar o ServeRest a entender o comportamento de sua infra?
140
+
141
+ ## Badge
142
+
143
+ Criou repositório utilizando o ServeRest? Adicione o código abaixo no topo do README.md para ter a badge do projeto.
144
+
145
+ [![Badge ServeRest](https://img.shields.io/badge/API-ServeRest-green)](https://github.com/ServeRest/ServeRest/)
146
+
147
+ ```markdown
148
+ [![Badge ServeRest](https://img.shields.io/badge/API-ServeRest-green)](https://github.com/ServeRest/ServeRest/)
149
+ ```
150
+
129
151
  ## Exemplos de automação
130
152
 
131
153
  Os repositórios abaixo são exemplos de automação com boas práticas e que consome o ServeRest.
132
154
 
133
155
  - [Java > Automação com REST-Assured e Junit - Lucas Fraga](https://github.com/uLucasFraga/restassured_for_studies)
134
156
  - [JS > Automação com Supertest, Mocha e Chai - Paulo Gonçalves](https://github.com/PauloGoncalvesBH/sample-supertest)
157
+ - [JS > Automação com Playwright - Leonard Tsuda](https://github.com/ltsuda/playwright-serverest)
135
158
  - [Python > Automação com Pytest - Leonardo Tsuda](https://github.com/ltsuda/pytest-serverest-study)
136
159
  - [Robot Framework > Automação com RequestsLibrary - Mayara Fernandes](https://github.com/mayribeirofernandes/testesrobotframework/tree/HEAD/ExemploAPI_ServeRest)
160
+ - [Ruby > Automação com HTTParty e RSpec - Bruno Quintanilha](https://github.com/braquintanilha/serverest-httparty-rspec)
137
161
 
138
- ## Badge [![Badge ServeRest](https://img.shields.io/badge/API-ServeRest-green)](https://github.com/ServeRest/ServeRest/)
139
-
140
- ```markdown
141
- [![Badge ServeRest](https://img.shields.io/badge/API-ServeRest-green)](https://github.com/ServeRest/ServeRest/)
142
- ```
162
+ Para encontrar mais repositórios acesse https://github.com/search?q=serverest&type=Repositories
143
163
 
144
164
  ## Patrocinadores
145
165
 
package/docs/swagger.json CHANGED
@@ -1,13 +1,12 @@
1
1
  {
2
2
  "swagger": "2.0",
3
3
  "info": {
4
- "description": "**O ServeRest é um servidor REST que simula uma loja virtual com intuito de servir de material de estudos de testes de API.**\n\n_**Ajude o ServeRest informando se prefere a documentação atual ou a antiga [nesse formulário](https://forms.gle/9RePTUQfeoDEqFiy5), que demanda poucos segundos para ser respondido.**_\n\nEssa página documenta todas as rotas e como acessá-las. Para mais detalhes do ServeRest (como executar localmente utilizando Docker ou NPM, alterar timeout de autenticação, etc) acesse [o repositório do ServeRest](https://github.com/serverest/serverest).\n\n\nEstá enfrentando instabilidade em alguma rota? Acesse a [página de status](https://status.serverest.dev/) para acompanhar enquanto normalizamos o ambiente. Enquanto isso pode utilizar o ServeRest localmente, [veja como aqui](https://github.com/ServeRest/ServeRest#readme).\n\nMuito obrigado ♥ a todos que apoiam o projeto [financeiramente](https://opencollective.com/serverest#section-contributors) ou [com código, ideias e divulgação](https://github.com/ServeRest/ServeRest#contribuidores-).\n\nO ServeRest possui um front, com status em beta, não deixe de conhecer: [front.serverest.dev](https://front.serverest.dev).\n\nPrecisa de apoio? [Abra uma issue](https://github.com/ServeRest/ServeRest/issues) ou contate o mantenedor do projeto:\n",
4
+ "description": "**O ServeRest é uma API REST que simula uma loja virtual com intuito de servir de material de estudos de testes de API.**\n\n_**Deixe um star no repositorio: [github.com/ServeRest/ServeRest](https://github.com/ServeRest/ServeRest).**_\n\nCaso utilizar para teste de carga leia a seção '[Teste de Carga](https://github.com/ServeRest/ServeRest#teste-de-carga)'.\n\nEssa página documenta todas as rotas e como acessá-las. Para mais detalhes do ServeRest (como executar localmente utilizando Docker ou NPM, alterar timeout de autenticação, etc) acesse [o repositório do ServeRest](https://github.com/serverest/serverest).\n\n\nEstá enfrentando instabilidade em alguma rota? Acesse a [página de status](https://status.serverest.dev/) para acompanhar enquanto normalizamos o ambiente. Enquanto isso pode utilizar o ServeRest localmente, [veja como aqui](https://github.com/ServeRest/ServeRest#readme).\n\nMuito obrigado ♥ a todos que apoiam o projeto [financeiramente](https://opencollective.com/serverest#section-contributors) ou [com código, ideias e divulgação](https://github.com/ServeRest/ServeRest#contribuidores-).\n\nO ServeRest possui um front, com status em beta, não deixe de conhecer: [front.serverest.dev](https://front.serverest.dev).\n\nPrecisa de apoio? [Abra uma issue](https://github.com/ServeRest/ServeRest/issues) ou contate o mantenedor do projeto:\n",
5
5
  "version": "2.X.X",
6
6
  "title": "ServeRest",
7
7
  "contact": {
8
8
  "name": "Paulo Gonçalves",
9
- "url": "https://www.linkedin.com/in/paulo-goncalves/",
10
- "email": "paulorochag@hotmail.com"
9
+ "url": "https://www.linkedin.com/in/paulo-goncalves/"
11
10
  }
12
11
  },
13
12
  "host": "localhost:3000",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "serverest",
3
- "version": "2.24.2",
3
+ "version": "2.25.1",
4
4
  "description": "Servidor REST local de forma rápida e simples para estudo de testes de API",
5
5
  "author": "Paulo Gonçalves <paulorochag@hotmail.com> (https://www.linkedin.com/in/paulo-goncalves/)",
6
6
  "license": "GPL-3.0",
@@ -31,17 +31,19 @@
31
31
  "prepare": "is-ci || husky install",
32
32
  "commit": "cz",
33
33
  "start": "node ./src/server.js",
34
- "dev": "cross-env NODE_ENV=serverest-development nodemon -e json,js ./src/server.js --nodoc",
35
- "test:mutation": "cross-env NODE_ENV=serverest-test stryker run ./test/stryker.conf.js",
36
- "test:mutation:diff": "cross-env NODE_ENV=serverest-test stryker-diff-runner --path ./test/stryker.conf.js --branch trunk",
37
- "test": "cross-env NODE_ENV=serverest-test nyc mocha --config test/integration/.mocharc.js",
38
- "posttest": "nyc report --reporter=lcov",
34
+ "dev": "nodemon --legacy-watch -e json,js ./src/server.js --nodoc",
35
+ "test:mutation": "stryker run ./test/stryker.conf.js",
36
+ "test:mutation:diff": "stryker-diff-runner --path ./test/stryker.conf.js --branch trunk",
37
+ "test:unit": "nyc --report-dir ./coverage-unit mocha --config test/unit/.mocharc.js",
38
+ "test:integration": "nyc --report-dir ./coverage-integration mocha --config test/integration/.mocharc.js",
39
+ "merge-lcov": "npx lcov-result-merger@3.1.0 'coverage-**/lcov.info' 'lcov.info'",
39
40
  "lint": "standard",
40
41
  "lint:fix": "standard --fix",
41
42
  "lint:staged": "lint-staged",
42
- "test:contract": "cross-env NODE_ENV=serverest-test mocha test/contract --timeout 60000"
43
+ "test:contract": "mocha test/contract --timeout 60000"
43
44
  },
44
45
  "dependencies": {
46
+ "axios": "^0.21.1",
45
47
  "colors": "^1.4.0",
46
48
  "connect-timeout": "^1.9.0",
47
49
  "cors": "^2.8.5",
@@ -50,11 +52,13 @@
50
52
  "express-query-int": "^3.0.0",
51
53
  "express-status-monitor": "^1.3.3",
52
54
  "express-validation": "^3.0.8",
55
+ "is-ci": "^3.0.0",
53
56
  "jsonwebtoken": "^8.5.1",
54
57
  "moesif-nodejs": "^3.1.5",
55
58
  "morgan": "^1.10.0",
56
- "nedb": "^1.8.0",
59
+ "nedb-promises": "^5.0.0",
57
60
  "open": "^8.0.6",
61
+ "rate-limiter-flexible": "^2.3.1",
58
62
  "swagger-ui-express": "^4.1.4",
59
63
  "yargs": "^16.2.0"
60
64
  },
@@ -70,22 +74,21 @@
70
74
  "@semantic-release/github": "^7.2.1",
71
75
  "@semantic-release/npm": "^7.1.1",
72
76
  "@semantic-release/release-notes-generator": "^9.0.2",
73
- "@stryker-mutator/core": "^4.6.0",
77
+ "@stryker-mutator/core": "^5.3.0",
74
78
  "chai": "^4.3.4",
75
79
  "commitizen": "^4.2.3",
76
- "cross-env": "^7.0.3",
77
80
  "cz-conventional-changelog": "^3.3.0",
78
81
  "faker": "^5.5.3",
79
82
  "husky": "^6.0.0",
80
- "is-ci": "^3.0.0",
81
83
  "lint-staged": "^10.5.4",
82
84
  "mocha": "^8.3.2",
85
+ "nock": "^13.1.3",
83
86
  "nodemon": "^2.0.7",
84
87
  "nyc": "^15.1.0",
85
88
  "semantic-release-docker": "^2.2.0",
86
89
  "sinon": "^10.0.0",
87
90
  "standard": "^16.0.3",
88
- "stryker-diff-runner": "^2.3.5",
91
+ "stryker-diff-runner": "^2.3.7",
89
92
  "supertest": "^6.1.3"
90
93
  },
91
94
  "engines": {
package/src/app.js CHANGED
@@ -13,9 +13,10 @@ const swaggerUi = require('swagger-ui-express')
13
13
  const { formaDeExecucao, urlDocumentacao } = require('./utils/ambiente')
14
14
  const { conf } = require('./utils/conf')
15
15
  const errorHandler = require('./middlewares/error-handler')
16
- const logger = require('./utils/logger')
16
+ // const logger = require('./utils/logger')
17
17
  const { version } = require('../package.json')
18
18
  const swaggerDocument = require('../docs/swagger.json')
19
+ const rateLimiter = require('./middlewares/rate-limiter')
19
20
 
20
21
  const ehAmbienteDeTestes = process.env.NODE_ENV === 'serverest-test'
21
22
 
@@ -27,6 +28,7 @@ app.use(express.urlencoded({ extended: false }))
27
28
  app.use(queryParser())
28
29
  app.use(timeout())
29
30
  app.use(cors())
31
+ app.use(rateLimiter)
30
32
 
31
33
  app.disable('etag')
32
34
 
@@ -45,11 +47,11 @@ if (!conf.semHeaderDeSeguranca) {
45
47
  }
46
48
 
47
49
  /* istanbul ignore if */
48
- if (formaDeExecucao() === 'serverest.dev' || formaDeExecucao() === 'agilizei') {
50
+ if (!ehAmbienteDeTestes) {
49
51
  app.use(require('express-status-monitor')({ title: 'ServeRest Status' }))
50
52
  }
51
53
 
52
- logger(app)
54
+ // logger(app)
53
55
 
54
56
  /* istanbul ignore next */
55
57
  switch (formaDeExecucao()) {
@@ -85,7 +87,7 @@ app.use('/produtos', require('./routes/produtos-route'))
85
87
  app.use('/carrinhos', require('./routes/carrinhos-route'))
86
88
 
87
89
  app.use(errorHandler)
88
- app.use(async (req, res) => {
90
+ app.use((req, res) => {
89
91
  res.status(405).send({
90
92
  message: `Não é possível realizar ${req.method} em ${req.url}. Acesse ${urlDocumentacao()} para ver as rotas disponíveis e como utilizá-las.`
91
93
  })
@@ -44,6 +44,6 @@ exports.put = async (req, res) => {
44
44
  return res.status(400).send({ message: constant.NOME_JA_USADO })
45
45
  }
46
46
  const registroCriado = await service.createOrUpdateById(req.params.id, req.body)
47
- if (registroCriado) { return res.status(201).send({ message: constant.POST_SUCESS, _id: registroCriado._id }) }
47
+ if (registroCriado._id !== req.params.id) { return res.status(201).send({ message: constant.POST_SUCESS, _id: registroCriado._id }) }
48
48
  res.status(200).send({ message: constant.PUT_SUCESS })
49
49
  }
@@ -43,6 +43,6 @@ exports.put = async (req, res) => {
43
43
  return res.status(400).send({ message: constant.EMAIL_JA_USADO })
44
44
  }
45
45
  const registroCriado = await service.createOrUpdateById(req.params.id, req.body)
46
- if (registroCriado) { return res.status(201).send({ message: constant.POST_SUCESS, _id: registroCriado._id }) }
46
+ if (registroCriado._id !== req.params.id) { return res.status(201).send({ message: constant.POST_SUCESS, _id: registroCriado._id }) }
47
47
  res.status(200).send({ message: constant.PUT_SUCESS })
48
48
  }
@@ -0,0 +1,18 @@
1
+ /* istanbul ignore file */
2
+
3
+ const { RateLimiterMemory } = require('rate-limiter-flexible')
4
+
5
+ const rateLimiter = new RateLimiterMemory({
6
+ points: 150, // requests
7
+ duration: 1 // segundo por IP
8
+ })
9
+
10
+ // Adicionar header 'monitor: false' quando atingir o limite definido para não enviar informações para o moesif.
11
+ module.exports = async (req, res, next) => {
12
+ await rateLimiter.consume(req.ip)
13
+ .then(() => next())
14
+ .catch(() => {
15
+ req.headers.monitor = false
16
+ next()
17
+ })
18
+ }
package/src/server.js CHANGED
@@ -10,6 +10,8 @@ const open = require('open')
10
10
  const { version } = require('../package.json')
11
11
  const { formaDeExecucao, urlDocumentacao } = require('./utils/ambiente')
12
12
  const { conf } = require('./utils/conf')
13
+ const getRandomFinancialContributor = require('./utils/getRandomFinancialContributor')
14
+
13
15
  const DEFAULT_PORT = 3000
14
16
 
15
17
  const argv = require('yargs')
@@ -71,8 +73,8 @@ server.listen(port, async () => {
71
73
  } else if (formaDeExecucao() === 'docker') {
72
74
  console.log(colors.white.bold('Quer alterar porta de execução, timeout do token, etc? Execute'), colors.yellow.bold('docker run -p 3000:3000 paulogoncalvesbh/serverest --help'))
73
75
  }
74
- console.log(colors.white.bold('Para outras dúvidas acesse'), colors.yellow.bold('https://github.com/ServeRest/ServeRest'))
75
- console.log(colors.cyan.bold('Feito com'), colors.red.bold('♥'), colors.cyan.bold('para todos os QAs\n'))
76
+ console.log(colors.white.bold('Para outras dúvidas acesse'), colors.yellow.bold('github.com/ServeRest/ServeRest\n'))
77
+ console.log(colors.cyan.bold('Feito com'), colors.red.bold('♥'), colors.cyan.bold('para todos os QAs e apoiado por'), colors.red.bold(await getRandomFinancialContributor()), '\n')
76
78
  })
77
79
  server.on('error', onError)
78
80
  server.on('listening', onListening)
@@ -1,53 +1,29 @@
1
1
  'use strict'
2
2
 
3
- const Nedb = require('nedb')
3
+ const Datastore = require('nedb-promises')
4
4
  const { join } = require('path')
5
5
 
6
6
  const alterarValoresParaRegex = require('../utils/alterarValoresParaRegex')
7
7
  const authService = require('../services/auth-service')
8
8
  const usuariosService = require('../services/usuarios-service')
9
9
 
10
- const datastore = new Nedb({ filename: join(__dirname, '../data/carrinhos.db'), autoload: true })
10
+ const datastore = Datastore.create({ filename: join(__dirname, '../data/carrinhos.db'), autoload: true })
11
11
 
12
12
  exports.getAll = queryString => {
13
13
  queryString = alterarValoresParaRegex(queryString)
14
- return new Promise((resolve, reject) => {
15
- datastore.find(queryString, (err, resultado) => {
16
- /* istanbul ignore if */
17
- if (err) reject(err)
18
- resolve(resultado)
19
- })
20
- })
14
+ return datastore.find(queryString)
21
15
  }
22
16
 
23
17
  exports.getOne = id => {
24
- return new Promise((resolve, reject) => {
25
- datastore.findOne({ _id: id }, (err, carrinho) => {
26
- /* istanbul ignore if */
27
- if (err) reject(err)
28
- resolve(carrinho)
29
- })
30
- })
18
+ return datastore.findOne({ _id: id })
31
19
  }
32
20
 
33
21
  exports.existeCarrinho = pesquisa => {
34
- return new Promise((resolve, reject) => {
35
- datastore.count(pesquisa, (err, count) => {
36
- /* istanbul ignore if */
37
- if (err) reject(err)
38
- resolve(count !== 0)
39
- })
40
- })
22
+ return datastore.count(pesquisa)
41
23
  }
42
24
 
43
25
  exports.criarCarrinho = async body => {
44
- return new Promise((resolve, reject) => {
45
- datastore.insert(body, (err, novoProduto) => {
46
- /* istanbul ignore if */
47
- if (err) reject(err)
48
- resolve(novoProduto)
49
- })
50
- })
26
+ return datastore.insert(body)
51
27
  }
52
28
 
53
29
  exports.extrairProdutosDuplicados = arrayProdutos => {
@@ -62,13 +38,7 @@ exports.extrairProdutosDuplicados = arrayProdutos => {
62
38
  }
63
39
 
64
40
  exports.deleteById = async id => {
65
- return new Promise((resolve, reject) => {
66
- datastore.remove({ _id: id }, {}, (err, quantidadeRegistrosExcluidos) => {
67
- /* istanbul ignore if */
68
- if (err) reject(err)
69
- resolve(quantidadeRegistrosExcluidos)
70
- })
71
- })
41
+ return datastore.remove({ _id: id }, {})
72
42
  }
73
43
 
74
44
  exports.getCarrinhoDoUsuario = async (authorization) => {
@@ -1,72 +1,36 @@
1
1
  'use strict'
2
2
 
3
- const Nedb = require('nedb')
3
+ const Datastore = require('nedb-promises')
4
4
  const { join } = require('path')
5
5
 
6
6
  const alterarValoresParaRegex = require('../utils/alterarValoresParaRegex')
7
7
 
8
- const datastore = new Nedb({ filename: join(__dirname, '../data/produtos.db'), autoload: true })
8
+ const datastore = Datastore.create({ filename: join(__dirname, '../data/produtos.db'), autoload: true })
9
9
 
10
10
  exports.getAll = queryString => {
11
11
  queryString = alterarValoresParaRegex(queryString)
12
- return new Promise((resolve, reject) => {
13
- datastore.find(queryString, (err, resultado) => {
14
- /* istanbul ignore if */
15
- if (err) reject(err)
16
- resolve(resultado)
17
- })
18
- })
12
+ return datastore.find(queryString)
19
13
  }
20
14
 
21
15
  exports.getOne = id => {
22
- return new Promise((resolve, reject) => {
23
- datastore.findOne({ _id: id }, (err, produto) => {
24
- /* istanbul ignore if */
25
- if (err) reject(err)
26
- resolve(produto)
27
- })
28
- })
16
+ return datastore.findOne({ _id: id })
29
17
  }
30
18
 
31
19
  exports.getDadosDoProduto = queryString => {
32
- return new Promise((resolve, reject) => {
33
- datastore.findOne(queryString, (err, resultado) => {
34
- /* istanbul ignore if */
35
- if (err) reject(err)
36
- resolve(resultado)
37
- })
38
- })
20
+ return datastore.findOne(queryString)
39
21
  }
40
22
 
41
23
  exports.existeProduto = pesquisa => {
42
- return new Promise((resolve, reject) => {
43
- datastore.count(pesquisa, (err, count) => {
44
- /* istanbul ignore if */
45
- if (err) reject(err)
46
- resolve(count !== 0)
47
- })
48
- })
24
+ return datastore.count(pesquisa)
49
25
  }
50
26
 
51
27
  exports.criarProduto = async body => {
52
28
  body = formatarValores(body)
53
- return new Promise((resolve, reject) => {
54
- datastore.insert(body, (err, novoProduto) => {
55
- /* istanbul ignore if */
56
- if (err) reject(err)
57
- resolve(novoProduto)
58
- })
59
- })
29
+ return datastore.insert(body)
60
30
  }
61
31
 
62
32
  exports.deleteById = async id => {
63
- return new Promise((resolve, reject) => {
64
- datastore.remove({ _id: id }, {}, (err, quantidadeRegistrosExcluidos) => {
65
- /* istanbul ignore if */
66
- if (err) reject(err)
67
- resolve(quantidadeRegistrosExcluidos)
68
- })
69
- })
33
+ return datastore.remove({ _id: id }, {})
70
34
  }
71
35
 
72
36
  exports.createOrUpdateById = async (idDoProdutoQueSeraAlterado, body) => {
@@ -75,13 +39,7 @@ exports.createOrUpdateById = async (idDoProdutoQueSeraAlterado, body) => {
75
39
  }
76
40
 
77
41
  exports.updateById = async (idDoProdutoQueSeraAlterado, body) => {
78
- return new Promise((resolve, reject) => {
79
- datastore.update({ _id: idDoProdutoQueSeraAlterado }, body, { upsert: true }, (err, quantidadeRegistrosAlterados, registroCriado) => {
80
- /* istanbul ignore if */
81
- if (err) reject(err)
82
- resolve(registroCriado)
83
- })
84
- })
42
+ return datastore.update({ _id: idDoProdutoQueSeraAlterado }, body, { upsert: true, returnUpdatedDocs: true })
85
43
  }
86
44
 
87
45
  function formatarValores (body) {
@@ -1,89 +1,42 @@
1
1
  'use strict'
2
2
 
3
- const Nedb = require('nedb')
3
+ const Datastore = require('nedb-promises')
4
4
  const { join } = require('path')
5
5
 
6
6
  const alterarValoresParaRegex = require('../utils/alterarValoresParaRegex')
7
7
 
8
- const datastore = new Nedb({ filename: join(__dirname, '../data/usuarios.db'), autoload: true })
8
+ const datastore = Datastore.create({ filename: join(__dirname, '../data/usuarios.db'), autoload: true })
9
9
 
10
10
  exports.getAll = queryString => {
11
11
  queryString = alterarValoresParaRegex(queryString)
12
- return new Promise((resolve, reject) => {
13
- datastore.find(queryString, (err, resultado) => {
14
- /* istanbul ignore if */
15
- if (err) reject(err)
16
- resolve(resultado)
17
- })
18
- })
12
+ return datastore.find(queryString)
19
13
  }
20
14
 
21
15
  exports.getOne = id => {
22
- return new Promise((resolve, reject) => {
23
- datastore.findOne({ _id: id }, (err, usuario) => {
24
- /* istanbul ignore if */
25
- if (err) reject(err)
26
- resolve(usuario)
27
- })
28
- })
16
+ return datastore.findOne({ _id: id })
29
17
  }
30
18
 
31
19
  exports.getDadosDoUsuario = queryString => {
32
- return new Promise((resolve, reject) => {
33
- datastore.findOne(queryString, (err, resultado) => {
34
- /* istanbul ignore if */
35
- if (err) reject(err)
36
- resolve(resultado)
37
- })
38
- })
20
+ return datastore.findOne(queryString)
39
21
  }
40
22
 
41
- exports.existeUsuario = pesquisa => {
42
- return new Promise((resolve, reject) => {
43
- datastore.count(pesquisa, (err, count) => {
44
- /* istanbul ignore if */
45
- if (err) reject(err)
46
- resolve(count !== 0)
47
- })
48
- })
23
+ exports.existeUsuario = async pesquisa => {
24
+ return datastore.count(pesquisa)
49
25
  }
50
26
 
51
- exports.usuarioEhAdministrador = ({ email, password }) => {
52
- return new Promise((resolve, reject) => {
53
- datastore.find({ email, password }, (err, resultado) => {
54
- /* istanbul ignore if */
55
- if (err) reject(err)
56
- resolve(JSON.parse(resultado[0].administrador))
57
- })
58
- })
27
+ exports.usuarioEhAdministrador = async ({ email, password }) => {
28
+ const resultado = await datastore.find({ email, password })
29
+ return JSON.parse(resultado[0].administrador)
59
30
  }
60
31
 
61
32
  exports.createUser = async body => {
62
- return new Promise((resolve, reject) => {
63
- datastore.insert(body, (err, novoUsuario) => {
64
- /* istanbul ignore if */
65
- if (err) reject(err)
66
- resolve(novoUsuario)
67
- })
68
- })
33
+ return datastore.insert(body)
69
34
  }
70
35
 
71
36
  exports.deleteById = async id => {
72
- return new Promise((resolve, reject) => {
73
- datastore.remove({ _id: id }, {}, (err, quantidadeRegistrosExcluidos) => {
74
- /* istanbul ignore if */
75
- if (err) reject(err)
76
- resolve(quantidadeRegistrosExcluidos)
77
- })
78
- })
37
+ return datastore.remove({ _id: id }, {})
79
38
  }
80
39
 
81
40
  exports.createOrUpdateById = async (idDoUsuarioQueSeraAlterado, body) => {
82
- return new Promise((resolve, reject) => {
83
- datastore.update({ _id: idDoUsuarioQueSeraAlterado }, body, { upsert: true }, (err, quantidadeRegistrosAlterados, registroCriado) => {
84
- /* istanbul ignore if */
85
- if (err) reject(err)
86
- resolve(registroCriado)
87
- })
88
- })
41
+ return datastore.update({ _id: idDoUsuarioQueSeraAlterado }, body, { upsert: true, returnUpdatedDocs: true })
89
42
  }
@@ -0,0 +1,24 @@
1
+ 'use strict'
2
+
3
+ const axios = require('axios')
4
+
5
+ module.exports = async () => {
6
+ const { data } = await axios.get('https://opencollective.com/serverest/members/all.json')
7
+ const userArray = removeAdminAndHostUser(data)
8
+ let arrayNameUsers = getOnlyNameFromAllUsers(userArray)
9
+ arrayNameUsers = removeDuplicatedValuesFromArray(arrayNameUsers)
10
+ const randomFinancialContributor = arrayNameUsers[Math.floor(Math.random() * arrayNameUsers.length)]
11
+ return randomFinancialContributor
12
+ }
13
+
14
+ const removeAdminAndHostUser = userArray => {
15
+ return userArray.filter((user) => user.role !== 'ADMIN' && user.role !== 'HOST' && user.name !== 'Paulo Gonçalves')
16
+ }
17
+
18
+ const getOnlyNameFromAllUsers = userArray => {
19
+ return Object.keys(userArray).map((key) => userArray[key].name)
20
+ }
21
+
22
+ const removeDuplicatedValuesFromArray = array => {
23
+ return [...new Set(array)]
24
+ }