serverest 2.24.3 → 2.25.2

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,94 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.25.2](https://github.com/ServeRest/ServeRest/compare/v2.25.1...v2.25.2) (2021-12-08)
4
+
5
+
6
+ ### Miscellaneous
7
+
8
+ * Revert "chore(patch): desabilitar monitoramento enquanto ajusto rate limit" ([36f69ce](https://github.com/ServeRest/ServeRest/commit/36f69ceca224a3f90e47a9a950dc5bc376f9e468))
9
+
10
+ ## [2.25.1](https://github.com/ServeRest/ServeRest/compare/v2.25.0...v2.25.1) (2021-11-23)
11
+
12
+
13
+ ### Chores
14
+
15
+ * **patch:** desabilitar monitoramento enquanto ajusto rate limit ([fb5098b](https://github.com/ServeRest/ServeRest/commit/fb5098bea9253e7606d8d5c66f252bf9a6870a3c))
16
+
17
+
18
+ ### Continuous Integration
19
+
20
+ * **environment:** limit prod secrets to trunk and beta branch ([56fb980](https://github.com/ServeRest/ServeRest/commit/56fb980d9d6add7cc92e96277421ff3a1db3a2c2))
21
+
22
+
23
+ ### Documentation
24
+
25
+ * **readme:** include playwright automation repo ([492400c](https://github.com/ServeRest/ServeRest/commit/492400c6bbdf3ce48b092e38c1eadc6ac8a0e410))
26
+
27
+ # [2.25.0](https://github.com/ServeRest/ServeRest/compare/v2.24.4...v2.25.0) (2021-11-22)
28
+
29
+
30
+ ### Chores
31
+
32
+ * criar multi-stage build para execução do projeto com nodemon ([9b8bca5](https://github.com/ServeRest/ServeRest/commit/9b8bca520a67eeaa0d08b3f1323a4cc515d38dd3))
33
+ * **docker:** avoid using 'prepare' on prod image ([bc4a9c7](https://github.com/ServeRest/ServeRest/commit/bc4a9c710fe7a91f27bd991dcfd31a260cbad6c8))
34
+ * **dockerfile:** incluir labels com informações do projeto ([7cbdd6c](https://github.com/ServeRest/ServeRest/commit/7cbdd6c0c60a7907941d1fd5dd2ea30a6d823f17))
35
+ * generate package-lock with newer version of npm ([e7b28a0](https://github.com/ServeRest/ServeRest/commit/e7b28a028c6d9ac547e58c4f12774a211578655a))
36
+ * guarantee that pipeline will break when test fail ([22a9629](https://github.com/ServeRest/ServeRest/commit/22a962982096b40fb7420beca3241161b7aa7f4c))
37
+ * **infra-test:** containerize infra test to easier run ([ad9529d](https://github.com/ServeRest/ServeRest/commit/ad9529dfeda47eacf487b947eec6b4bec7d28fe1))
38
+ * renomear test de api para teste de integração ([1368f38](https://github.com/ServeRest/ServeRest/commit/1368f38c186212d2307884dc0ee434c5ae8996a1))
39
+ * set specific version of base images ([ca4c152](https://github.com/ServeRest/ServeRest/commit/ca4c152ae3174376912977ade20119047f60b8fc))
40
+ * **sonar:** remover análise de coverage de arquivos que não necessitam ter testes ([9f5ae1f](https://github.com/ServeRest/ServeRest/commit/9f5ae1f3e28d71d860b8a58d68b4c3a030cde83b))
41
+ * **test:** exibir cor na execução de teste de integração para facilitar leitura ([44ef82d](https://github.com/ServeRest/ServeRest/commit/44ef82d6e2ea4a1f130d767f40e0341a8489a256))
42
+
43
+
44
+ ### Continuous Integration
45
+
46
+ * explicitar o nome da imagem docker ([a2eb8c2](https://github.com/ServeRest/ServeRest/commit/a2eb8c238e55acffc7de3b5149120b2627505090))
47
+ * remover execução de teste que não está containerizado ([123eb10](https://github.com/ServeRest/ServeRest/commit/123eb106101bc56201e188c3a925182fce0dc7e1))
48
+
49
+
50
+ ### Documentation
51
+
52
+ * **contributing:** detalhar a seção de testes com os pacotes utilizados e informação de coverage ([687395e](https://github.com/ServeRest/ServeRest/commit/687395e6e145384c4ac93af096b95bc01f480f2e))
53
+ * **readme:** adicionar repositório de automação em ruby ([bd828af](https://github.com/ServeRest/ServeRest/commit/bd828af2b993e3ef4558e130ed5252a287d52c9c))
54
+
55
+
56
+ ### Features
57
+
58
+ * **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))
59
+
60
+
61
+ ### Tests
62
+
63
+ * fix infra test error ([6345210](https://github.com/ServeRest/ServeRest/commit/634521029dadc92ba3e0b52775b008c7c80bf37f))
64
+ * **infra:** avoid test caching ([befbf6e](https://github.com/ServeRest/ServeRest/commit/befbf6e7d7318964d86f94cb4f12dcdb9b3ff407))
65
+ * **unitario:** garantir comportamento do método getRandomFinancialContributor ([d4debd7](https://github.com/ServeRest/ServeRest/commit/d4debd7691255e307dcef61c986d7486cfc51d30))
66
+ * utilizar multi-stage build ([ed69b62](https://github.com/ServeRest/ServeRest/commit/ed69b6269178ec13382f643a22226fc4dcfe2fe4))
67
+
68
+ ## [2.24.4](https://github.com/ServeRest/ServeRest/compare/v2.24.3...v2.24.4) (2021-10-13)
69
+
70
+
71
+ ### Chores
72
+
73
+ * **makefile:** executar as imagens utilizando 'docker-compose up' ao invés de run ([d8f3885](https://github.com/ServeRest/ServeRest/commit/d8f3885f6ec9c5d43ca51ddd32f46c6a42940991))
74
+ * bump stryker-mutator and stryker-diff-runner to latest ([e9fa90d](https://github.com/ServeRest/ServeRest/commit/e9fa90d5d04f70ecb07d08142b6e48fa02a747ed))
75
+
76
+
77
+ ### Code Refactoring
78
+
79
+ * **database:** alterar o banco de dados para um fork atualizado e com promise implementado ([ee2eca3](https://github.com/ServeRest/ServeRest/commit/ee2eca33ee38b4b51f32c0b9d88876bf0a761ce7))
80
+
81
+
82
+ ### Continuous Integration
83
+
84
+ * executar webhook encima de commit deployado ([da7c099](https://github.com/ServeRest/ServeRest/commit/da7c099b42e79e033e823b230e58d928386b1df5))
85
+ * fixar versão do semantic-release ([bc37107](https://github.com/ServeRest/ServeRest/commit/bc37107683771ca4e0103f35bef2908f2e9b9a4f))
86
+
87
+
88
+ ### Documentation
89
+
90
+ * **patch:** detalhar sobre como usar para teste de carga ([c676d7a](https://github.com/ServeRest/ServeRest/commit/c676d7acd96f4d5d4c0d70479aef9cd455beb862))
91
+
3
92
  ## [2.24.3](https://github.com/ServeRest/ServeRest/compare/v2.24.2...v2.24.3) (2021-08-07)
4
93
 
5
94
 
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.3",
3
+ "version": "2.25.2",
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,11 +31,12 @@
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",
34
+ "dev": "nodemon --legacy-watch -e json,js ./src/server.js --nodoc",
35
35
  "test:mutation": "stryker run ./test/stryker.conf.js",
36
36
  "test:mutation:diff": "stryker-diff-runner --path ./test/stryker.conf.js --branch trunk",
37
- "test": "nyc mocha --config test/integration/.mocharc.js",
38
- "posttest": "nyc report --reporter=lcov",
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",
@@ -51,11 +52,13 @@
51
52
  "express-query-int": "^3.0.0",
52
53
  "express-status-monitor": "^1.3.3",
53
54
  "express-validation": "^3.0.8",
55
+ "is-ci": "^3.0.0",
54
56
  "jsonwebtoken": "^8.5.1",
55
57
  "moesif-nodejs": "^3.1.5",
56
58
  "morgan": "^1.10.0",
57
- "nedb": "^1.8.0",
59
+ "nedb-promises": "^5.0.0",
58
60
  "open": "^8.0.6",
61
+ "rate-limiter-flexible": "^2.3.1",
59
62
  "swagger-ui-express": "^4.1.4",
60
63
  "yargs": "^16.2.0"
61
64
  },
@@ -71,22 +74,21 @@
71
74
  "@semantic-release/github": "^7.2.1",
72
75
  "@semantic-release/npm": "^7.1.1",
73
76
  "@semantic-release/release-notes-generator": "^9.0.2",
74
- "@stryker-mutator/core": "^4.6.0",
77
+ "@stryker-mutator/core": "^5.3.0",
75
78
  "chai": "^4.3.4",
76
79
  "commitizen": "^4.2.3",
77
- "cross-env": "^7.0.3",
78
80
  "cz-conventional-changelog": "^3.3.0",
79
81
  "faker": "^5.5.3",
80
82
  "husky": "^6.0.0",
81
- "is-ci": "^3.0.0",
82
83
  "lint-staged": "^10.5.4",
83
84
  "mocha": "^8.3.2",
85
+ "nock": "^13.1.3",
84
86
  "nodemon": "^2.0.7",
85
87
  "nyc": "^15.1.0",
86
88
  "semantic-release-docker": "^2.2.0",
87
89
  "sinon": "^10.0.0",
88
90
  "standard": "^16.0.3",
89
- "stryker-diff-runner": "^2.3.5",
91
+ "stryker-diff-runner": "^2.3.7",
90
92
  "supertest": "^6.1.3"
91
93
  },
92
94
  "engines": {
package/src/app.js CHANGED
@@ -16,6 +16,7 @@ const errorHandler = require('./middlewares/error-handler')
16
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,7 +47,7 @@ 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
 
@@ -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
+ }
@@ -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
  }