├── .babelrc ├── .editorconfig ├── .eslintrc.json ├── .gitignore ├── .npmignore ├── .nycrc ├── .travis.yml ├── LICENSE.md ├── README-pt-br.md ├── README.md ├── app.js ├── bin └── www.js ├── components └── mock │ ├── mock.api.js │ ├── mock.controller.js │ ├── mock.helper.js │ ├── mock.js │ ├── mock.spec.js │ └── users.json ├── config └── cors.js ├── package.json ├── scripts ├── build.sh ├── create.js ├── dev.sh ├── lint.sh ├── prod.sh ├── refactor.js ├── start.sh └── test.sh └── test ├── cors.spec.js └── www.spec.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["@babel/preset-env"], 3 | "env": { 4 | "test": { 5 | "plugins": ["istanbul"] 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see https://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "node": true, 4 | "es6": true, 5 | "mocha": true 6 | }, 7 | "extends": "eslint:recommended", 8 | "globals": { 9 | "Atomics": "readonly", 10 | "SharedArrayBuffer": "readonly" 11 | }, 12 | "parserOptions": { 13 | "ecmaVersion": 2018, 14 | "sourceType": "module" 15 | }, 16 | "rules": { 17 | "no-console": "off" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | /.nyc_output 8 | /json-server-api/users.json 9 | 10 | # dependencies 11 | /node_modules 12 | 13 | # profiling files 14 | chrome-profiler-events.json 15 | speed-measure-plugin.json 16 | 17 | # IDEs and editors 18 | /.idea 19 | .project 20 | .classpath 21 | .c9/ 22 | *.launch 23 | .settings/ 24 | *.sublime-workspace 25 | 26 | # IDE - VSCode 27 | .vscode/* 28 | !.vscode/settings.json 29 | !.vscode/tasks.json 30 | !.vscode/launch.json 31 | !.vscode/extensions.json 32 | .history/* 33 | 34 | # misc 35 | /.sass-cache 36 | /connect.lock 37 | /coverage 38 | /libpeerconnection.log 39 | npm-debug.log 40 | yarn-error.log 41 | package-lock.json 42 | testem.log 43 | /typings 44 | 45 | 46 | # System Files 47 | .DS_Store 48 | Thumbs.db 49 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .nyc_output 3 | .babelrc 4 | .editorconfig 5 | .eslintrc.json 6 | .gitignore 7 | .nycrc 8 | .travis.yml 9 | bin 10 | components 11 | config 12 | node_modules 13 | scripts 14 | test 15 | app.js 16 | package-lock.json 17 | -------------------------------------------------------------------------------- /.nycrc: -------------------------------------------------------------------------------- 1 | { 2 | "require": [ 3 | "@babel/register" 4 | ], 5 | "sourceMap": false, 6 | "instrument": false, 7 | "reporter": [ 8 | "text", 9 | "html" 10 | ], 11 | "exclude": [ 12 | "tests/**" 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: node_js 3 | node_js: 4 | - 'stable' 5 | addons: 6 | code_climate: 7 | repo_token: 8 | secure: "cxIq5JaW/BWJGB7txYNTgx5sMyrzSq5tn+8/lrENJjeyJ+7uYBSh+Qt9WMRcsM9JF788K782mGruPysgqz4oZ5SB5+fECKWYMog+mmfsGdr0Mk7mI36H31owtOjNPcuRtXhKgTvHSnq2aQCbqd9EKTmIiiGd6l7zigJYn4M6uFHR2sBGsZRRB/s+1FIq6sCB+KxsVurJUIqE76ylG6JceY97AWnIETwHLO1hQY0Bxy09CeK+lKCxZeIFPAKc3B7Qv01Mr97Ho4sBx3CBxgrbS31dQm7yCW+NtaXKkZ8APaSJyczn2WdpEjGz01Co/VGr5BvbtFGXwSG4AeZmaWkz4Ok4R88sJb85ZhpLqZTdQbbGPgLWkQgT08WMhfEyR1RJgl6LaacYeP7GKXgr4PDzOFhSuN+7Df3AjAwNUAZJKDckmlxwgyFSr4w69eCGt30/+9hdQdilwgkaCxWLqFWIh3mOkwVmOqCJtyXLSQBPOU8Nz07sywEck0nvVv+wqeyzobKWuG9t2EtIN+sQWFoosnbJvdfLzzXEzNIMeCGp3NiOKOr1JDIhgn/6M7tVVMccZ7cSew67/O1Y2nVupfLnMOrp64uFKgIKFacy/Q4AZ8TOFgwnTAnX/fXY4HphvG8Hi3dw29ZEguoUWqIqyarfFnBCyOv7iE0nbMt/yAQ/owA=" 9 | cache: 10 | directories: 11 | - node_modules 12 | before_install: 13 | - npm update 14 | install: 15 | - npm install 16 | before_script: 17 | - npm install codeclimate-test-reporter -g 18 | script: 19 | - npm run coverage 20 | after_script: 21 | - codeclimate-test-reporter < ./coverage/lcov.info 22 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) Copyright 2017 Thiago Luiz Nunes 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README-pt-br.md: -------------------------------------------------------------------------------- 1 | # mock-user-auth 2 | 3 | ![npm](https://img.shields.io/npm/dt/mock-user-auth.svg) 4 | [![npm version](https://badge.fury.io/js/mock-user-auth.svg)](https://badge.fury.io/js/mock-user-auth) 5 | [![Build Status](https://travis-ci.org/thiagoluiznunes/mock-user-auth.svg?branch=master)](https://travis-ci.org/thiagoluiznunes/mock-user-auth) 6 | [![Maintainability](https://api.codeclimate.com/v1/badges/b60e5e0c37609f6b21c0/maintainability)](https://codeclimate.com/github/thiagoluiznunes/mock-json-server/maintainability) 7 | [![Test Coverage](https://api.codeclimate.com/v1/badges/b60e5e0c37609f6b21c0/test_coverage)](https://codeclimate.com/github/thiagoluiznunes/mock-json-server/test_coverage) 8 | [![Issue Count](https://codeclimate.com/github/thiagoluiznunes/mock-json-server/badges/issue_count.svg)](https://codeclimate.com/github/thiagoluiznunes/mock-json-server/issues) 9 | 10 | 11 | --- 12 | Mock-User-Auth é uma API de autenticação de usuário mock desenvolvida em Nodejs e Express utilizando JWT como autenticador na versão ES6 do JavaScript. 13 | 14 | **Objetivo**: pode ser usado para ajudar no desenvolvimento do front-end. É simples e rápido, você só precisa seguir os passos abaixo. 15 | 16 | 17 | Ferramentas: Node.js | Express.js | Mocha | Chai | Istanbul 18 | 19 | ### Requerimentos ### 20 | 21 | * **[Node.js 11.x](http://nodejs.org/en/)** :white_check_mark: 22 | * **[Npm 6.x](https://www.npmjs.com/)** :white_check_mark: 23 | 24 | ### Npm ### 25 | 1 - Instalando pacote via npm: 26 | ``` 27 | $ npm i --save mock-user-auth 28 | ``` 29 | 2 - Criando script no package.json: 30 | ```json 31 | { 32 | "script": { 33 | "dev": "nodemon ./node_modules/mock-user-auth/bin/www.js" 34 | } 35 | } 36 | ``` 37 | 3 - Iniciando api: 38 | ``` 39 | $ npm run dev 40 | ``` 41 | **Opção: Você pode definir a porta após o comando npm:** 42 | ``` 43 | $ npm run dev 8080 44 | ``` 45 | 46 | ### Instalação do Projeto ### 47 | 48 | **Obs.: As seguintes instruções foram testadas na distribuição do Ubuntu.** 49 | 50 | 1 - Depois de clonar o repositório 'git clone' (comando), execute os seguintes comandos para instalar as dependências do projeto: 51 | - user@user:~/diretorio_projeto_clonado/$ **npm install** 52 | - **Instale manualmente as dependências que podem não ter sido instaladas pelo comando acima.** :white_check_mark: 53 | 54 | 2 - Iniciar aplicação 55 | - use@user:~/diretorio_projeto_clonado/ **npm start** 56 | - Acesse pelo nevagador http://localhost:3000/api/v1/users 57 | 58 | ### Rotas da API ### 59 | | Ação | Requerido | Método | URL 60 | | -----------------------|------------|----------|-------------- 61 | | AUTENTICAR USUÁRIO | | `POST` | /api/v1/auth 62 | | CRIAR USUÁRIO | | `POST` | /api/v1/users 63 | | OBTER USUÁRIO | Autenticar | `GET` | /api/v1/users 64 | | ATUALIZAR USUÁRIO | Autenticar | `PATCH` | /api/v1/users 65 | | DELETAR USUÁRIO | Autenticar | `DELETE` | /api/v1/users 66 | | DELETAR TODOS USUÁRIOS | | `DELETE` | /api/v1/users 67 | 68 | #### AUTENTICAR USUÁRIO #### 69 | * REQUISIÇÃO 70 | ``` 71 | POST /api/v1/auth 72 | ``` 73 | ```json 74 | { 75 | "email": "user@gmail.com", 76 | "password": "user123" 77 | } 78 | ``` 79 | * RESPOSTA 80 | ```json 81 | { 82 | "token": "eyJhbGciOiJI..." 83 | } 84 | ``` 85 | 86 | #### CRIAR USUÁRIO #### 87 | * REQUISIÇÃO 88 | ``` 89 | POST /api/v1/users 90 | ``` 91 | ```json 92 | { 93 | "name": "user", 94 | "email": "user@gmail.com", 95 | "password": "user123" 96 | } 97 | ``` 98 | * RESPOSTA 99 | ```json 100 | { 101 | "message": "User registered with success", 102 | "token": "eyJhbGciOiJI..." 103 | } 104 | ``` 105 | 106 | #### OBTER USUÁRIO POR TOKEN #### 107 | * REQUISIÇÃO 108 | ``` 109 | GET /api/v1/users 110 | ``` 111 | ```javascript 112 | const token = 'eyJhbGciOiJI...'; 113 | req.setRequestHeader('Authorization', token); 114 | ``` 115 | * RESPOSTA 116 | ```json 117 | { 118 | "id": 46643, 119 | "name": "user", 120 | "email": "user@gmail.com", 121 | "password": "user123", 122 | "imageUrl": "https://almsaeedstudio.com/themes/AdminLTE/dist/img/user2-160x160.jpg" 123 | } 124 | ``` 125 | 126 | #### ATUALIZAR USUÁRIO POR TOKEN #### 127 | * REQUISIÇÃO 128 | ``` 129 | PATCH /api/v1/users 130 | ``` 131 | ```javascript 132 | const token = 'eyJhbGciOiJI...'; 133 | req.setRequestHeader('Authorization', token); 134 | ``` 135 | ```json 136 | { 137 | "name": "newName", 138 | "email": "new_email@gmail.com", 139 | "password": "newpassword123" 140 | } 141 | ``` 142 | * RESPOSTA 143 | ```json 144 | { 145 | "message": "User updated with success" 146 | } 147 | ``` 148 | 149 | #### DELETAR USUÁRIO POR TOKEN #### 150 | * REQUISIÇÃO 151 | ``` 152 | DELETE /api/v1/users 153 | ``` 154 | ```javascript 155 | const token = 'eyJhbGciOiJI...'; 156 | req.setRequestHeader('Authorization', token); 157 | ``` 158 | * RESPOSTA 159 | ```json 160 | { 161 | "message": "User deleted with success" 162 | } 163 | ``` 164 | 165 | #### DELETAR TODOS USUÁRIOS #### 166 | * REQUISIÇÃO 167 | ``` 168 | DELETE /api/v1/all-users 169 | ``` 170 | ```json 171 | { 172 | "key_admin": "keyadmin123" 173 | } 174 | ``` 175 | * RESPOSTA 176 | ```json 177 | { 178 | "message": "Users deleted with success" 179 | } 180 | ``` 181 | 182 | ### Autor 183 | 184 | * Thiago Luiz Pereira Nunes ([ThiagoLuizNunes](https://github.com/ThiagoLuizNunes)) thiagoluiz.dev@gmail.com 185 | 186 | ### Licença 187 | 188 | Este projeto está licenciado sob a licença MIT - consulte o arquivo [LICENSE.md](LICENSE.md) para obter detalhes 189 | 190 | >Criado por **[ThiagoLuizNunes](https://www.linkedin.com/in/thiago-luiz-507483112/)** 2019. 191 | 192 | --- 193 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mock-user-auth 2 | 3 | ![npm](https://img.shields.io/npm/dt/mock-user-auth.svg) 4 | [![npm version](https://badge.fury.io/js/mock-user-auth.svg)](https://badge.fury.io/js/mock-user-auth) 5 | [![Build Status](https://travis-ci.org/thiagoluiznunes/mock-user-auth.svg?branch=master)](https://travis-ci.org/thiagoluiznunes/mock-user-auth) 6 | [![Maintainability](https://api.codeclimate.com/v1/badges/b60e5e0c37609f6b21c0/maintainability)](https://codeclimate.com/github/thiagoluiznunes/mock-json-server/maintainability) 7 | [![Test Coverage](https://api.codeclimate.com/v1/badges/b60e5e0c37609f6b21c0/test_coverage)](https://codeclimate.com/github/thiagoluiznunes/mock-json-server/test_coverage) 8 | [![Issue Count](https://codeclimate.com/github/thiagoluiznunes/mock-json-server/badges/issue_count.svg)](https://codeclimate.com/github/thiagoluiznunes/mock-json-server/issues) 9 | 10 |   11 | 12 | **[README.md pt-br](https://github.com/thiagoluiznunes/mock-user-auth/blob/master/README-pt-br.md)** 13 | 14 | --- 15 | Mock-User-Auth is a mock user authentication API developed in Nodejs and Express using JWT as an authenticator in the ES6 version of JavaScript. 16 | 17 | **The use**: It can be used to assist your front-end development. It's simple and fast, you just need to follow the steps below. 18 | 19 | 20 | Toolkit: Node.js | Express.js | Mocha | Chai | Istanbul 21 | 22 | ### Requirements ### 23 | 24 | * **[Node.js 11.x](http://nodejs.org/en/)** :white_check_mark: 25 | * **[Npm 6.x](https://www.npmjs.com/)** :white_check_mark: 26 | 27 | ### Npm ### 28 | 1 - Install package: 29 | ``` 30 | $ npm i --save mock-user-auth 31 | ``` 32 | 2 - Create script in package.json: 33 | ```json 34 | { 35 | "script": { 36 | "dev": "nodemon ./node_modules/mock-user-auth/bin/www.js" 37 | } 38 | } 39 | ``` 40 | 3 - Start api: 41 | ``` 42 | $ npm run dev 43 | ``` 44 | **Option: You can set the port after npm command:** 45 | ``` 46 | $ npm run dev 8080 47 | ``` 48 | 49 | 50 | ### Project Installation ### 51 | 52 | **Obs.: The following instructions were tested on Ubuntu distribution.** 53 | 54 | 1 - After 'git clone' command, run the following commands to install dependencies: 55 | - user@user:~/path_to_cloned_folder/$ **npm install** 56 | - **Manually install the dependencies that may have not been installed by the above command.** :white_check_mark: 57 | 58 | 2 - Start application 59 | - use@user:~/path_to_cloned_folder/ **npm start** 60 | - Access the browser http://localhost:3000/api/v1/users 61 | 62 | ### API Routes ### 63 | | Action | Required | Method | URL 64 | | ------------------|----------|----------|-------------- 65 | | AUTHENTICATE USER | | `POST` | /api/v1/auth 66 | | CREATE USER | | `POST` | /api/v1/users 67 | | GET USER | Auth | `GET` | /api/v1/users 68 | | PATCH USER | Auth | `PATCH` | /api/v1/users 69 | | DELETE USER | Auth | `DELETE` | /api/v1/users 70 | | DELETE ALL USERS | | `DELETE` | /api/v1/users 71 | 72 | #### AUTHENTICATE USER #### 73 | * REQUEST 74 | ``` 75 | POST /api/v1/auth 76 | ``` 77 | ```json 78 | { 79 | "email": "user@gmail.com", 80 | "password": "user123" 81 | } 82 | ``` 83 | * RESPONSE 84 | ```json 85 | { 86 | "token": "eyJhbGciOiJI..." 87 | } 88 | ``` 89 | 90 | #### CREATE USER #### 91 | * REQUEST 92 | ``` 93 | POST /api/v1/users 94 | ``` 95 | ```json 96 | { 97 | "name": "user", 98 | "email": "user@gmail.com", 99 | "password": "user123" 100 | } 101 | ``` 102 | * RESPONSE 103 | ```json 104 | { 105 | "message": "User registered with success", 106 | "token": "eyJhbGciOiJI..." 107 | } 108 | ``` 109 | 110 | #### GET USER BY TOKEN #### 111 | * REQUEST 112 | ``` 113 | GET /api/v1/users 114 | ``` 115 | ```javascript 116 | const token = 'eyJhbGciOiJI...'; 117 | req.setRequestHeader('Authorization', token); 118 | ``` 119 | * RESPONSE 120 | ```json 121 | { 122 | "id": 46643, 123 | "name": "user", 124 | "email": "user@gmail.com", 125 | "password": "user123", 126 | "imageUrl": "https://almsaeedstudio.com/themes/AdminLTE/dist/img/user2-160x160.jpg" 127 | } 128 | ``` 129 | 130 | #### PATCH USER BY TOKEN #### 131 | * REQUEST 132 | ``` 133 | PATCH /api/v1/users 134 | ``` 135 | ```javascript 136 | const token = 'eyJhbGciOiJI...'; 137 | req.setRequestHeader('Authorization', token); 138 | ``` 139 | ```json 140 | { 141 | "name": "newName", 142 | "email": "new_email@gmail.com", 143 | "password": "newpassword123" 144 | } 145 | ``` 146 | * RESPONSE 147 | ```json 148 | { 149 | "message": "User updated with success" 150 | } 151 | ``` 152 | 153 | #### DELETE USER BY TOKEN #### 154 | * REQUEST 155 | ``` 156 | DELETE /api/v1/users 157 | ``` 158 | ```javascript 159 | const token = 'eyJhbGciOiJI...'; 160 | req.setRequestHeader('Authorization', token); 161 | ``` 162 | * RESPONSE 163 | ```json 164 | { 165 | "message": "User deleted with success" 166 | } 167 | ``` 168 | 169 | #### DELETE ALL USERS #### 170 | * REQUEST 171 | ``` 172 | DELETE /api/v1/all-users 173 | ``` 174 | ```json 175 | { 176 | "key_admin": "keyadmin123" 177 | } 178 | ``` 179 | * RESPONSE 180 | ```json 181 | { 182 | "message": "Users deleted with success" 183 | } 184 | ``` 185 | 186 | ### Authors 187 | 188 | * Thiago Luiz Pereira Nunes ([ThiagoLuizNunes](https://github.com/ThiagoLuizNunes)) thiagoluiz.dev@gmail.com 189 | 190 | ### License 191 | 192 | This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details 193 | 194 | >Created By **[ThiagoLuizNunes](https://www.linkedin.com/in/thiago-luiz-507483112/)** 2019. 195 | 196 | --- 197 | -------------------------------------------------------------------------------- /app.js: -------------------------------------------------------------------------------- 1 | import createError from 'http-errors'; 2 | import express from 'express'; 3 | import bodyParser from 'body-parser'; 4 | import logger from 'morgan'; 5 | import cors from './config/cors'; 6 | import mock from './components/mock/mock'; 7 | 8 | const app = express(); 9 | 10 | app.use(logger('dev')); 11 | app.use(cors); 12 | app.use(express.json()); 13 | app.use(express.urlencoded({ extended: true })); 14 | app.use(bodyParser.json()); 15 | 16 | app.use('/api/v1', mock.api); 17 | 18 | // catch 404 and forward to error handler 19 | app.use((req, res, next) => { 20 | next(createError(404)); 21 | }); 22 | 23 | // error handler 24 | app.use((err, req, res, next) => { 25 | // set locals, only providing error in development 26 | res.locals.message = err.message; 27 | res.locals.error = req.app.get('env') === 'development' ? err : {}; 28 | 29 | // render the error page 30 | res.status(err.status || 500); 31 | res.render('error'); 32 | }); 33 | 34 | export default app; 35 | -------------------------------------------------------------------------------- /bin/www.js: -------------------------------------------------------------------------------- 1 | import "@babel/polyfill"; 2 | import app from '../app'; 3 | import debug from 'debug'; 4 | import http from 'http'; 5 | 6 | debug('mock-auth-user:server'); 7 | 8 | const port = normalizePort(process.env.PORT || process.argv[2] || '3000'); 9 | 10 | app.set('port', port); 11 | 12 | const server = http.createServer(app); 13 | 14 | server.listen(port); 15 | server.on('error', onError); 16 | server.on('listening', onListening); 17 | 18 | function normalizePort(val) { 19 | if (process.env.NODE_ENV === 'test') { 20 | return 3001; 21 | } 22 | const port = parseInt(val, 10); 23 | 24 | if (isNaN(port)) { 25 | // named pipe 26 | return val; 27 | } 28 | if (port >= 0) { 29 | // port number 30 | return port; 31 | } 32 | return false; 33 | } 34 | 35 | function onError(error) { 36 | if (error.syscall !== 'listen') { 37 | throw error; 38 | } 39 | 40 | const bind = typeof port === 'string' 41 | ? 'Pipe ' + port 42 | : 'Port ' + port; 43 | 44 | // handle specific listen errors with friendly messages 45 | switch (error.code) { 46 | case 'EACCES': 47 | console.error(bind + ' requires elevated privileges'); 48 | process.exit(1); 49 | break; 50 | case 'EADDRINUSE': 51 | console.error(bind + ' is already in use'); 52 | process.exit(1); 53 | break; 54 | default: 55 | throw error; 56 | } 57 | } 58 | 59 | function onListening() { 60 | const addr = server.address(); 61 | const bind = typeof addr === 'string' 62 | ? 'pipe ' + addr 63 | : 'port ' + addr.port; 64 | debug('Listening on ' + bind); 65 | } 66 | 67 | export { server, normalizePort, onError }; 68 | -------------------------------------------------------------------------------- /components/mock/mock.api.js: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import ctrl from './mock.controller'; 3 | import helper from './mock.helper'; 4 | const router = express.Router(); 5 | 6 | const resHandler = (res, code, message) => { 7 | res.status(code).json({ message: message }); 8 | } 9 | 10 | // const responseFactory = async (req, res, message) => { 11 | // const token = await helper.retrieveRequestToken(req); 12 | // const response = await ctrl.deleteUser(token, req.body); 13 | // if (!response.status) return resHandler(res, 403, message.error); 14 | // res.status(200).json({ message: message.error }); 15 | // } 16 | 17 | router.post('/auth', helper.asyncMiddleware(async (req, res) => { 18 | const { email, password } = req.body; 19 | const response = await ctrl.isAuthenticated(email, password); 20 | 21 | if (!response.status || response.data === null) return resHandler(res, 401, 'Incorrect email or password'); 22 | const id = response.data; 23 | const access_token = ctrl.createToken({ email, id }); 24 | res.status(200).json({ token: access_token }); 25 | })); 26 | 27 | router.post('/users', helper.asyncMiddleware(async (req, res) => { 28 | const { name, email, password } = req.body; 29 | const imageUrl = 'https://almsaeedstudio.com/themes/AdminLTE/dist/img/user2-160x160.jpg'; 30 | const response = await ctrl.postUser(name, email, password, imageUrl); 31 | 32 | if (!response.status) return resHandler(res, 401, 'User already registered'); 33 | res.status(200).json({ message: 'User registered with success', token: response.token }); 34 | })); 35 | 36 | router.get('/users', helper.asyncMiddleware(async (req, res) => { 37 | const authorization = 'authorization'; 38 | let token = req.body.token || req.query.token || req.headers[authorization]; 39 | const response = await ctrl.getUser(token); 40 | if (!response.status || response.data === null) return resHandler(res, 403, 'Unauthorized'); 41 | res.status(200).json(response.data); 42 | })); 43 | 44 | router.patch('/users', helper.asyncMiddleware(async (req, res) => { 45 | const token = await helper.retrieveRequestToken(req); 46 | const response = await ctrl.updateUser(token, req.body); 47 | if (!response.status) return resHandler(res, 403, response.data); 48 | res.status(200).json({ data: response.data, message: 'User updated with success!' }); 49 | })); 50 | 51 | router.delete('/users', helper.asyncMiddleware(async (req, res) => { 52 | const token = await helper.retrieveRequestToken(req); 53 | const response = await ctrl.deleteUser(token, req.body); 54 | if (!response.status) return resHandler(res, 403, 'Unauthorized to delete'); 55 | res.status(200).json({ message: 'User deleted with success!' }); 56 | })); 57 | 58 | router.delete('/all-users', helper.asyncMiddleware(async (req, res) => { 59 | const { key_admin } = req.body; 60 | if (key_admin === 'keyadmin123') { 61 | ctrl.deleteAllUsers(); 62 | resHandler(res, 200, 'Users deleted with success'); 63 | } else { 64 | resHandler(res, 403, 'Unauthorized access'); 65 | } 66 | })); 67 | 68 | export default router; 69 | -------------------------------------------------------------------------------- /components/mock/mock.controller.js: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import faker from 'faker'; 3 | import jwt from 'jsonwebtoken'; 4 | 5 | const SECRET_KEY = 'authsecret123'; 6 | const expiresIn = '24h'; 7 | const userdb = JSON.parse(fs.readFileSync(__dirname + '/users.json', 'UTF-8')); 8 | 9 | const createToken = (payload) => { 10 | return jwt.sign(payload, SECRET_KEY, { expiresIn }); 11 | } 12 | 13 | const verifyToken = async (token) => { 14 | let data, status, res_decode; 15 | await jwt.verify(token, SECRET_KEY, (err, decode) => { 16 | if (err) { 17 | data = err.message; 18 | status = false; 19 | } 20 | else { 21 | res_decode = decode; 22 | } 23 | }); 24 | return { data, status, res_decode }; 25 | } 26 | 27 | const deleteAllUsers = async () => { 28 | userdb.users = []; 29 | await fs.writeFileSync(__dirname + '/users.json', JSON.stringify(userdb, null, 2), 'utf8'); 30 | return true; 31 | } 32 | 33 | const isAuthenticated = async (email, password) => { 34 | let id = undefined; 35 | let res = false; 36 | await userdb.users.findIndex(user => { 37 | if (user.email === email && user.password === password) { 38 | id = user.id; 39 | res = true; 40 | } 41 | }); 42 | return { data: id, status: res }; 43 | } 44 | 45 | const postUser = async (name, email, password, imageUrl) => { 46 | let exist = false; 47 | await userdb.users.findIndex(user => { 48 | if (user.email === email) { 49 | exist = true; 50 | } 51 | }); 52 | 53 | if (!exist) { 54 | const id = await faker.random.number(); 55 | const newUser = { 56 | id: id, 57 | name: name, 58 | email: email, 59 | password: password, 60 | imageUrl: imageUrl 61 | } 62 | await userdb.users.push(newUser); 63 | fs.writeFileSync(__dirname + '/users.json', JSON.stringify(userdb, null, 2), 'utf8'); 64 | const token = await createToken(newUser); 65 | return { data: token, status: true }; 66 | } else { 67 | return { data: undefined, status: false } 68 | } 69 | } 70 | 71 | const getUser = async (token) => { 72 | let { data, res_decode, status } = await verifyToken(token); 73 | if (res_decode) { 74 | await userdb.users.findIndex(user => { 75 | if (user.email === res_decode.email && user.id === res_decode.id) { 76 | data = user; 77 | status = true; 78 | } 79 | }); 80 | } 81 | return { data: data, status: status }; 82 | } 83 | 84 | const updateUser = async (token, body) => { 85 | let { data, res_decode, status } = await verifyToken(token); 86 | if (res_decode) { 87 | await userdb.users.findIndex(user => { 88 | if (user.email === res_decode.email && user.id === res_decode.id) { 89 | user.name = body.name ? body.name : user.name; 90 | user.email = body.email ? body.email : user.email; 91 | user.password = body.password ? body.password : user.password; 92 | user.imageUrl = body.imageUrl ? body.imageUrl : user.imageUrl; 93 | data = user; 94 | status = true; 95 | } 96 | }); 97 | fs.writeFileSync(__dirname + '/users.json', JSON.stringify(userdb, null, 2), 'utf8'); 98 | } 99 | return { data: data, status: status }; 100 | } 101 | 102 | const deleteUser = async (token) => { 103 | let { res_decode, status } = await verifyToken(token); 104 | if (res_decode) { 105 | await userdb.users.findIndex((user, index) => { 106 | if (user.email === res_decode.email && user.id === res_decode.id) { 107 | userdb.users.splice(index, 1); 108 | status = true; 109 | } 110 | }); 111 | fs.writeFileSync(__dirname + '/users.json', JSON.stringify(userdb, null, 2), 'utf8'); 112 | } 113 | return { status: status }; 114 | } 115 | 116 | export default { 117 | createToken, 118 | isAuthenticated, 119 | postUser, 120 | getUser, 121 | updateUser, 122 | deleteUser, 123 | deleteAllUsers, 124 | } 125 | -------------------------------------------------------------------------------- /components/mock/mock.helper.js: -------------------------------------------------------------------------------- 1 | const asyncMiddleware = fn => 2 | (req, res, next) => { 3 | Promise.resolve(fn(req, res, next)) 4 | .catch(next); 5 | }; 6 | 7 | const retrieveRequestToken = async (req) => { 8 | const authorization = 'authorization'; 9 | let token = req.body.token || req.query.token || req.headers[authorization]; 10 | return token; 11 | } 12 | 13 | export default { asyncMiddleware, retrieveRequestToken }; 14 | -------------------------------------------------------------------------------- /components/mock/mock.js: -------------------------------------------------------------------------------- 1 | import api from './mock.api'; 2 | import controller from './mock.controller'; 3 | 4 | export default { 5 | api, 6 | controller 7 | } 8 | -------------------------------------------------------------------------------- /components/mock/mock.spec.js: -------------------------------------------------------------------------------- 1 | process.env.NODE_ENV = 'test'; 2 | 3 | import chai from 'chai'; 4 | import chaiHttp from 'chai-http'; 5 | import mock from './mock'; 6 | import { server } from '../../bin/www'; 7 | 8 | const assert = chai.assert; 9 | const expect = chai.expect; 10 | 11 | const user = { 12 | name: 'user', 13 | email: 'user@test.com', 14 | password: 'user123' 15 | } 16 | 17 | const userPost = (bool) => { 18 | mock.controller.postUser('controller', 'controller@test.com', 'controller123', 'https://') 19 | .then(res => { 20 | expect(res.status).to.be.an('boolean'); 21 | expect(res.status).to.equal(bool); 22 | }); 23 | } 24 | 25 | describe('Mock Module', () => { 26 | it('It should be a module', () => { 27 | assert.typeOf(mock, 'Object'); 28 | }); 29 | it('It should be a express router function ', () => { 30 | assert.typeOf(mock.api, 'function'); 31 | }); 32 | it('It should be a object ', () => { 33 | assert.typeOf(mock.controller, 'Object'); 34 | }); 35 | }); 36 | 37 | describe('Mock Controller', () => { 38 | describe('IsAuthenticated Function', () => { 39 | it('It should check the function return ', () => { 40 | mock.controller.isAuthenticated(user.email, user.password) 41 | .then(res => { 42 | expect(res.status).to.be.an('boolean'); 43 | }); 44 | }); 45 | }); 46 | describe('Delete All Users Function', () => { 47 | it('It should delete all users', () => { 48 | mock.controller.deleteAllUsers() 49 | .then(res => { 50 | expect(res).to.equal(true); 51 | }); 52 | }); 53 | }); 54 | describe('PostUser Function', () => { 55 | it('It should insert a new user', () => { 56 | userPost(true); 57 | }); 58 | it('It should block the insertion of existent user', () => { 59 | userPost(false); 60 | }); 61 | }); 62 | }); 63 | 64 | chai.use(chaiHttp); 65 | 66 | const deleteAllUsersRequest = (key, code) => { 67 | chai.request(server) 68 | .delete('/api/v1/all-users') 69 | .send({ key_admin: key }) 70 | .end((err, res) => { 71 | expect(res.status).to.equal(code); 72 | }); 73 | } 74 | 75 | const userPostRequest = (code, message) => { 76 | chai.request(server) 77 | .post('/api/v1/users') 78 | .send(user) 79 | .end((err, res) => { 80 | expect(res.status).to.equal(code); 81 | expect(res.body).to.be.an('Object'); 82 | expect(res.body.message).to.be.equal(message); 83 | }); 84 | } 85 | 86 | const userAuthRequest = (code, data) => { 87 | chai.request(server) 88 | .post('/api/v1/auth') 89 | .send(data) 90 | .end((err, res) => { 91 | expect(res.status).to.equal(code); 92 | expect(res.body).to.be.an('Object'); 93 | }); 94 | } 95 | 96 | const userGetRequest = (code, data) => { 97 | chai.request(server) 98 | .get('/api/v1/users') 99 | .set('Authorization', data) 100 | .end((err, res) => { 101 | expect(res.body).to.be.an('Object'); 102 | expect(res.body).to.be.not.empty; 103 | expect(res.status).to.equal(code); 104 | }); 105 | } 106 | 107 | const userDeleteRequest = (code, token) => { 108 | chai.request(server) 109 | .delete('/api/v1/users') 110 | .set('Authorization', token) 111 | .end((err, res) => { 112 | expect(res.status).to.equal(code); 113 | }); 114 | } 115 | 116 | const userPatchRequest = (code, token, body) => { 117 | chai.request(server) 118 | .patch('/api/v1/users') 119 | .set('Authorization', token, body) 120 | .end((err, res) => { 121 | expect(res.status).to.equal(code); 122 | expect(res.body).to.be.an('Object'); 123 | expect(res.body).to.be.not.empty; 124 | }); 125 | } 126 | 127 | const retriveUserToken = async () => { 128 | let token; 129 | await userPostRequest(200, 'User registered with success'); 130 | await chai.request(server) 131 | .post('/api/v1/auth') 132 | .send(user) 133 | .then((res) => { 134 | token = res.body.token; 135 | }) 136 | .catch((err) => { 137 | throw err; 138 | }); 139 | return token; 140 | } 141 | 142 | describe('Mock Api', () => { 143 | describe('/DELETE Users 200', () => { 144 | it('It should delete all users', () => { 145 | deleteAllUsersRequest('keyadmin123', 200); 146 | }); 147 | }); 148 | describe('/DELETE Users 403', () => { 149 | it('It should not delete all users', () => { 150 | deleteAllUsersRequest('wrongpassword', 403); 151 | }); 152 | }); 153 | 154 | describe('/POST User 200', () => { 155 | it('It should create a new user', () => { 156 | userPostRequest(200, 'User registered with success'); 157 | }); 158 | }); 159 | describe('/POST User 401', () => { 160 | it('It should not create a new user', () => { 161 | userPostRequest(401, 'User already registered'); 162 | }); 163 | }); 164 | describe('/Auth User 200', () => { 165 | after(() => { 166 | deleteAllUsersRequest('keyadmin123', 200); 167 | 168 | }); 169 | it('It should authenticate user', () => { 170 | userAuthRequest(200, user); 171 | }); 172 | }); 173 | describe('/Auth User 401', () => { 174 | it(`It shouldn't authenticate user`, () => { 175 | userAuthRequest(401, { name: 'user', email: 'user@test.com', password: 'wrongpassword' }); 176 | }); 177 | }); 178 | describe('/GET User 200', () => { 179 | let token; 180 | before(async () => { 181 | token = await retriveUserToken(); 182 | }); 183 | after(() => { 184 | deleteAllUsersRequest('keyadmin123', 200); 185 | }); 186 | it('It should get a user by token', () => { 187 | userGetRequest(200, token); 188 | }); 189 | }); 190 | describe('/GET User 403', () => { 191 | it('It should not get a user by token', () => { 192 | userGetRequest(403, 'wrongtoken'); 193 | }); 194 | }); 195 | 196 | describe('/PATCH User 200', () => { 197 | after(() => { 198 | deleteAllUsersRequest('keyadmin123', 200); 199 | }); 200 | it('It should update a user by token', async () => { 201 | const token = await retriveUserToken(); 202 | userPatchRequest(200, token, { name: 'newTestName' }); 203 | }); 204 | }); 205 | describe('/GET User 403', () => { 206 | it('It should not update a user by token', () => { 207 | userPatchRequest(403, 'wrongtoken', { name: 'newTestName' }); 208 | }); 209 | }); 210 | 211 | describe('/DELETE User 200', () => { 212 | after(() => { 213 | deleteAllUsersRequest('keyadmin123', 200); 214 | }); 215 | it('It should update a user by token', async () => { 216 | const token = await retriveUserToken(); 217 | userDeleteRequest(200, token); 218 | }); 219 | }); 220 | describe('/DELETE User 403', () => { 221 | it('It should not update a user by token', () => { 222 | userDeleteRequest(403, 'wrongtoken'); 223 | }); 224 | }); 225 | }); 226 | -------------------------------------------------------------------------------- /components/mock/users.json: -------------------------------------------------------------------------------- 1 | { 2 | "users": [] 3 | } -------------------------------------------------------------------------------- /config/cors.js: -------------------------------------------------------------------------------- 1 | export default (req, res, next) => { 2 | res.setHeader('Access-Control-Allow-Origin', '*'); 3 | res.setHeader( 4 | 'Access-Control-Allow-Methods', 5 | 'OPTIONS, GET, POST, PUT, PATCH, DELETE' 6 | ); 7 | res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); 8 | if (req.method === 'OPTIONS') { 9 | return res.sendStatus(200); 10 | } 11 | next(); 12 | }; 13 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mock-user-auth", 3 | "version": "1.0.13", 4 | "description": "Mock-User-Auth is a mock user authentication API developed in Nodejs and Express using JWT as an authenticator", 5 | "private": false, 6 | "author": "Thiago Luiz Nunes (https://github.com/thiagoluiznunes)", 7 | "license": "MIT", 8 | "scripts": { 9 | "dev": "scripts/dev.sh", 10 | "build": "scripts/build.sh", 11 | "start": "scripts/start.sh", 12 | "lint": "scripts/lint.sh", 13 | "test": "scripts/test.sh", 14 | "coverage": "nyc --reporter=lcov npm test" 15 | }, 16 | "dependencies": { 17 | "@babel/polyfill": "7.4.4", 18 | "body-parser": "1.18.3", 19 | "debug": "~2.6.9", 20 | "express": "~4.16.0", 21 | "faker": "4.1.0", 22 | "http-errors": "~1.6.2", 23 | "jsonwebtoken": "8.5.1", 24 | "morgan": "~1.9.0", 25 | "nodemon": "1.18.11" 26 | }, 27 | "devDependencies": { 28 | "@babel/cli": "7.4.4", 29 | "@babel/core": "7.4.5", 30 | "@babel/node": "7.4.5", 31 | "@babel/preset-env": "7.4.5", 32 | "babel-plugin-istanbul": "5.1.4", 33 | "babel-polyfill": "6.26.0", 34 | "chai": "4.2.0", 35 | "chai-http": "4.2.1", 36 | "eslint": "5.16.0", 37 | "eslint-config-airbnb-base": "13.1.0", 38 | "eslint-plugin-import": "2.17.3", 39 | "mocha": "6.1.2", 40 | "mocha-lcov-reporter": "1.3.0", 41 | "nyc": "13.3.0" 42 | }, 43 | "engines": { 44 | "node": "11.x", 45 | "npm": "6.x" 46 | }, 47 | "keywords": [ 48 | "JSON", 49 | "server", 50 | "express", 51 | "node", 52 | "http", 53 | "fake", 54 | "REST", 55 | "API", 56 | "prototyping", 57 | "mock", 58 | "mocking", 59 | "test", 60 | "testing", 61 | "rest", 62 | "data", 63 | "json-server", 64 | "middleware", 65 | "auth", 66 | "authentication", 67 | "authorization", 68 | "jwt", 69 | "chai", 70 | "mocha", 71 | "istanbul", 72 | "babel", 73 | "coverage" 74 | ], 75 | "directories": { 76 | "test": "test" 77 | }, 78 | "repository": { 79 | "type": "git", 80 | "url": "git+https://github.com/ThiagoLuizNunes/mock-json-server.git" 81 | }, 82 | "bugs": { 83 | "url": "https://github.com/ThiagoLuizNunes/mock-json-server/issues" 84 | }, 85 | "homepage": "https://github.com/ThiagoLuizNunes/mock-json-server#readme" 86 | } 87 | -------------------------------------------------------------------------------- /scripts/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | rm -rf ./dist 3 | ./node_modules/.bin/babel ./bin --out-dir dist/bin 4 | ./node_modules/.bin/babel ./components --out-dir dist/components 5 | ./node_modules/.bin/babel ./config --out-dir dist/config 6 | ./node_modules/.bin/babel ./app.js --out-dir dist 7 | ./node_modules/.bin/babel ./scripts/create.js --out-dir dist/scripts 8 | cp components/mock/users.json dist/components/mock 9 | cp package.json dist/ 10 | cp README.md dist/ 11 | cp LICENSE.md dist/ 12 | node ./scripts/refactor.js 13 | 14 | -------------------------------------------------------------------------------- /scripts/create.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | const fs = require('fs'); 3 | const package_json = JSON.parse(fs.readFileSync('./package.json', 'UTF-8')); 4 | package_json.scripts.mock = 'nodemon ./node_modules/mock-user-auth/bin/www.js'; 5 | fs.writeFileSync('./package.json', JSON.stringify(package_json, null, 2), 'utf8'); 6 | -------------------------------------------------------------------------------- /scripts/dev.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | ./node_modules/.bin/nodemon --exec babel-node ./bin/www 3 | -------------------------------------------------------------------------------- /scripts/lint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | ./node_modules/.bin/eslint ./bin/*.js ./components/**/*.js ./config/*.js 3 | -------------------------------------------------------------------------------- /scripts/prod.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | npm i pm2 --sav--dev 3 | ./node_modules/.bin/pm2 start ./dist/bin/www.js 4 | ./node_modules/.bin/pm2 monit 5 | -------------------------------------------------------------------------------- /scripts/refactor.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | const fs = require('fs'); 3 | const package_json = JSON.parse(fs.readFileSync('./dist/package.json', 'UTF-8')); 4 | package_json.scripts = { 5 | "postinstall": "node ./scripts/create.js" 6 | }; 7 | fs.writeFileSync('./dist/package.json', JSON.stringify(package_json, null, 2), 'utf8'); 8 | -------------------------------------------------------------------------------- /scripts/start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | ./node_modules/.bin/nodemon --exec ./node_modules/.bin/babel-node ./bin/www 3 | #./node_modules/.bin/babel-node ./bin/www 4 | #./node_modules/.bin/nodemon ./dist/bin/www 5 | 6 | -------------------------------------------------------------------------------- /scripts/test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | NODE_ENV=test ./node_modules/.bin/mocha --require @babel/register --require babel-polyfill ./components/**/*.spec.js ./**/*.spec.js 3 | -------------------------------------------------------------------------------- /test/cors.spec.js: -------------------------------------------------------------------------------- 1 | process.env.NODE_ENV = 'test'; 2 | 3 | import chai from 'chai'; 4 | import chaiHttp from 'chai-http'; 5 | import { server } from '../bin/www'; 6 | 7 | const expect = chai.expect; 8 | 9 | chai.use(chaiHttp); 10 | 11 | describe('Cors middleware', () => { 12 | it('It should return 200', () => { 13 | chai.request(server) 14 | .options('/api/v1/') 15 | .end((err, res) => { 16 | expect(res.statusCode).to.equal(200); 17 | }); 18 | }); 19 | it('It should pass request', () => { 20 | chai.request(server) 21 | .get('/api/v1/') 22 | .end((err, res) => { 23 | expect(res.statusCode).to.equal(404); 24 | }); 25 | }); 26 | }); 27 | -------------------------------------------------------------------------------- /test/www.spec.js: -------------------------------------------------------------------------------- 1 | process.env.NODE_ENV = 'test'; 2 | 3 | import chai from 'chai'; 4 | import chaiHttp from 'chai-http'; 5 | import { server, normalizePort, onError } from '../bin/www'; 6 | 7 | const assert = chai.assert; 8 | const expect = chai.expect; 9 | 10 | chai.use(chaiHttp); 11 | 12 | describe('WWW server', () => { 13 | describe('NormalizePort Function', () => { 14 | it('It should return 3001 port', () => { 15 | const port = normalizePort(); 16 | expect(port).to.be.a('number'); 17 | expect(port).to.equal(3001); 18 | }); 19 | it('It should return false', () => { 20 | process.env.NODE_ENV = 'default'; 21 | const port = normalizePort(-3001); 22 | expect(port).to.equal(false); 23 | }); 24 | it('It should return number', () => { 25 | after(() => { 26 | process.env.NODE_ENV = 'test'; 27 | }); 28 | process.env.NODE_ENV = 'default'; 29 | const port = normalizePort('4500'); 30 | expect(port).to.be.a('number'); 31 | expect(port).to.equal(4500); 32 | }); 33 | it('It should return isNaN', () => { 34 | after(() => { 35 | process.env.NODE_ENV = 'test'; 36 | }); 37 | process.env.NODE_ENV = 'default'; 38 | const port = normalizePort('isNaN'); 39 | expect(port).not.be.a('number'); 40 | expect(port).to.equal('isNaN'); 41 | }); 42 | }); 43 | 44 | describe('OnError Function', () => { 45 | it('It should throw exception', () => { 46 | try { 47 | expect(onError({ syscall: 'isNotSyscall' })).to.throw(); 48 | } catch (err) { 49 | expect(err).to.be.a('Object'); 50 | expect(err.syscall).to.equal('isNotSyscall'); 51 | } 52 | }); 53 | it('It should catch default error', () => { 54 | try { 55 | expect(onError({ syscall: 'listen', code: 'Default' })).to.throw(); 56 | } catch (err) { 57 | expect(err).to.be.a('Object'); 58 | expect(err.code).to.equal('Default'); 59 | } 60 | }); 61 | // it('It should catch EACCES error', () => { 62 | // try { 63 | // expect(onError({ syscall: 'listen', code: 'EACCES' })).to.throw(); 64 | // } catch (err) {} 65 | // }); 66 | // it('It should catch EADDRINUSE error', () => { 67 | // try { 68 | // expect(onError({ syscall: 'listen', code: 'EADDRINUSE' })).to.throw(); 69 | // } catch (err) {} 70 | // }); 71 | }); 72 | }); 73 | --------------------------------------------------------------------------------