├── .env.sample ├── .eslintignore ├── .eslintrc ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── change_request.md │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE.md └── stale.yml ├── .gitignore ├── .huskyrc ├── .lintstagedrc ├── .prettierignore ├── .prettierrc ├── LICENCE.md ├── README.md ├── _config.yml ├── app.js ├── bin └── www.js ├── config.js ├── docs └── index.md ├── package.json ├── src ├── components │ ├── db │ │ └── setup.js │ └── user │ │ ├── controller.js │ │ ├── index.js │ │ ├── index.spec.js │ │ └── validator.js ├── docs │ ├── index.js │ └── swagger.yml └── schemas │ └── user.js └── test └── index.js /.env.sample: -------------------------------------------------------------------------------- 1 | APP_ENV={development|production} 2 | PORT= 3 | ATLAS_URL_PRODUCTION= 4 | ATLAS_URL_TEST=mongodb://localhost:27017/test -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | /bin/www.js -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["airbnb-base", "prettier"], 3 | "parserOptions": { 4 | "ecmaVersion": 2018 5 | }, 6 | "env": { 7 | "browser": true, 8 | "node": true, 9 | "es6": true, 10 | "mocha": true 11 | }, 12 | "plugins": [], 13 | "rules": { 14 | "no-use-before-define": ["error", { "functions": true, "classes": true }], 15 | "import/extensions": ["off", "never"], 16 | "no-unused-vars": [ 17 | "error", 18 | { 19 | "varsIgnorePattern": "should|expect" 20 | } 21 | ] 22 | }, 23 | "overrides": [ 24 | { 25 | "files": ["*.test.js", "*.spec.js"], 26 | "rules": { 27 | "no-unused-expressions": "off" 28 | } 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | --- 8 | 9 | **Describe the bug** A clear and concise description of what the bug is. 10 | 11 | **To Reproduce** Steps to reproduce the behavior: 12 | 13 | 1. Go to '...' 14 | 2. Open file '....' 15 | 3. Go to Line '....' 16 | 4. Run '...' 17 | 5. See error 18 | 19 | **Expected behavior** A clear and concise description of what you expected to 20 | happen. 21 | 22 | **Screenshots** If applicable, add screenshots to help explain your problem. 23 | 24 | **Additional context** Add any other context about the problem here. 25 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/change_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Change Request 3 | about: For any changes in the existing design 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | --- 8 | 9 | **What should you change?** A clear and concise description of what changes are 10 | required 11 | 12 | **Why is that change required?** A clear and concise reason for the change. 13 | 14 | **Additional context** Add any other context or screenshots about the feature 15 | request here. 16 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | --- 8 | 9 | **Is your feature request related to a problem? Please describe.** A clear and 10 | concise description of what the problem is. Ex. I'm always frustrated when [...] 11 | 12 | **Describe the solution you'd like** A clear and concise description of what you 13 | want to happen. 14 | 15 | **Describe alternatives you've considered** A clear and concise description of 16 | any alternative solutions or features you've considered. 17 | 18 | **Additional context** Add any other context or screenshots about the feature 19 | request here. 20 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | **What this PR does / why we need it**: 4 | 5 | **Which issue this PR fixes** _(optional, in 6 | `fixes #(, fixes #, ...)` format, will close that 7 | issue when PR gets merged)_: fixes # 8 | 9 | **Checklist** 10 | 11 | - [ ] Does this PR have a corresponding GitHub issue? 12 | - [ ] Have you added debug messages where necessary? 13 | 14 | **Special notes for your reviewer**: 15 | -------------------------------------------------------------------------------- /.github/stale.yml: -------------------------------------------------------------------------------- 1 | # Number of days of inactivity before an issue becomes stale 2 | daysUntilStale: 60 3 | # Number of days of inactivity before a stale issue is closed 4 | daysUntilClose: 7 5 | # Issues with these labels will never be considered stale 6 | exemptLabels: 7 | - pinned 8 | - priority 9 | # Label to use when marking an issue as stale 10 | staleLabel: wontfix 11 | # Comment to post when marking an issue as stale. Set to `false` to disable 12 | markComment: > 13 | This issue has been automatically marked as stale because it has not had 14 | recent activity. It will be closed if no further activity occurs. Thank you 15 | for your contributions. 16 | # Comment to post when closing a stale issue. Set to `false` to disable 17 | closeComment: false -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.toptal.com/developers/gitignore/api/node 3 | # Edit at https://www.toptal.com/developers/gitignore?templates=node 4 | 5 | ### Node ### 6 | # Logs 7 | logs 8 | *.log 9 | npm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # Diagnostic reports (https://nodejs.org/api/report.html) 15 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 16 | 17 | # Runtime data 18 | pids 19 | *.pid 20 | *.seed 21 | *.pid.lock 22 | 23 | # Directory for instrumented libs generated by jscoverage/JSCover 24 | lib-cov 25 | 26 | # Coverage directory used by tools like istanbul 27 | coverage 28 | *.lcov 29 | 30 | # nyc test coverage 31 | .nyc_output 32 | 33 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 34 | .grunt 35 | 36 | # Bower dependency directory (https://bower.io/) 37 | bower_components 38 | 39 | # node-waf configuration 40 | .lock-wscript 41 | 42 | # Compiled binary addons (https://nodejs.org/api/addons.html) 43 | build/Release 44 | 45 | # Dependency directories 46 | node_modules/ 47 | jspm_packages/ 48 | 49 | # TypeScript v1 declaration files 50 | typings/ 51 | 52 | # TypeScript cache 53 | *.tsbuildinfo 54 | 55 | # Optional npm cache directory 56 | .npm 57 | 58 | # Optional eslint cache 59 | .eslintcache 60 | 61 | # Microbundle cache 62 | .rpt2_cache/ 63 | .rts2_cache_cjs/ 64 | .rts2_cache_es/ 65 | .rts2_cache_umd/ 66 | 67 | # Optional REPL history 68 | .node_repl_history 69 | 70 | # Output of 'npm pack' 71 | *.tgz 72 | 73 | # Yarn Integrity file 74 | .yarn-integrity 75 | 76 | # dotenv environment variables file 77 | .env 78 | .env.test 79 | 80 | # parcel-bundler cache (https://parceljs.org/) 81 | .cache 82 | 83 | # Next.js build output 84 | .next 85 | 86 | # Nuxt.js build / generate output 87 | .nuxt 88 | dist 89 | 90 | # Gatsby files 91 | .cache/ 92 | # Comment in the public line in if your project uses Gatsby and not Next.js 93 | # https://nextjs.org/blog/next-9-1#public-directory-support 94 | # public 95 | 96 | # vuepress build output 97 | .vuepress/dist 98 | 99 | # Serverless directories 100 | .serverless/ 101 | 102 | # FuseBox cache 103 | .fusebox/ 104 | 105 | # DynamoDB Local files 106 | .dynamodb/ 107 | 108 | # TernJS port file 109 | .tern-port 110 | 111 | # Stores VSCode versions used for testing VSCode extensions 112 | .vscode-test 113 | 114 | #custom 115 | .vscode 116 | yarn.lock 117 | package-*.lock 118 | 119 | 120 | # End of https://www.toptal.com/developers/gitignore/api/node -------------------------------------------------------------------------------- /.huskyrc: -------------------------------------------------------------------------------- 1 | { 2 | "hooks": { 3 | "pre-commit": "lint-staged" 4 | } 5 | } -------------------------------------------------------------------------------- /.lintstagedrc: -------------------------------------------------------------------------------- 1 | '*.js': 2 | - prettier --write 3 | - eslint --fix 4 | '*.{json,md}': 5 | - prettier --write 6 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .vscode 3 | .DS_Store 4 | yarn-*.log 5 | yarn.lock -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 80, 3 | "tabWidth": 4, 4 | "useTabs": true, 5 | "semi": true, 6 | "singleQuote": true, 7 | "trailingComma": "all", 8 | "bracketSpacing": true, 9 | "proseWrap": "always" 10 | } -------------------------------------------------------------------------------- /LICENCE.md: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and 10 | distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by the 13 | copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other 16 | entities that control, are controlled by, or are under common control with 17 | that entity. For the purposes of this definition, "control" means (i) the 18 | power, direct or indirect, to cause the direction or management of such 19 | entity, whether by contract or otherwise, or (ii) ownership of fifty percent 20 | (50%) or more of the outstanding shares, or (iii) beneficial ownership of 21 | such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity exercising 24 | permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation source, and 28 | configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical transformation 31 | or translation of a Source form, including but not limited to compiled 32 | object code, generated documentation, and conversions to other media types. 33 | 34 | "Work" shall mean the work of authorship, whether in Source or Object form, 35 | made available under the License, as indicated by a copyright notice that is 36 | included in or attached to the work (an example is provided in the Appendix 37 | below). 38 | 39 | "Derivative Works" shall mean any work, whether in Source or Object form, 40 | that is based on (or derived from) the Work and for which the editorial 41 | revisions, annotations, elaborations, or other modifications represent, as a 42 | whole, an original work of authorship. For the purposes of this License, 43 | Derivative Works shall not include works that remain separable from, or 44 | merely link (or bind by name) to the interfaces of, the Work and Derivative 45 | Works thereof. 46 | 47 | "Contribution" shall mean any work of authorship, including the original 48 | version of the Work and any modifications or additions to that Work or 49 | Derivative Works thereof, that is intentionally submitted to Licensor for 50 | inclusion in the Work by the copyright owner or by an individual or Legal 51 | Entity authorized to submit on behalf of the copyright owner. For the 52 | purposes of this definition, "submitted" means any form of electronic, 53 | verbal, or written communication sent to the Licensor or its 54 | representatives, including but not limited to communication on electronic 55 | mailing lists, source code control systems, and issue tracking systems that 56 | are managed by, or on behalf of, the Licensor for the purpose of discussing 57 | and improving the Work, but excluding communication that is conspicuously 58 | marked or otherwise designated in writing by the copyright owner as "Not a 59 | Contribution." 60 | 61 | "Contributor" shall mean Licensor and any individual or Legal Entity on 62 | behalf of whom a Contribution has been received by Licensor and subsequently 63 | incorporated within the Work. 64 | 65 | 2. Grant of Copyright License. Subject to the terms and conditions of this 66 | License, each Contributor hereby grants to You a perpetual, worldwide, 67 | non-exclusive, no-charge, royalty-free, irrevocable copyright license to 68 | reproduce, prepare Derivative Works of, publicly display, publicly perform, 69 | sublicense, and distribute the Work and such Derivative Works in Source or 70 | Object form. 71 | 72 | 3. Grant of Patent License. Subject to the terms and conditions of this License, 73 | each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, 74 | no-charge, royalty-free, irrevocable (except as stated in this section) 75 | patent license to make, have made, use, offer to sell, sell, import, and 76 | otherwise transfer the Work, where such license applies only to those patent 77 | claims licensable by such Contributor that are necessarily infringed by their 78 | Contribution(s) alone or by combination of their Contribution(s) with the 79 | Work to which such Contribution(s) was submitted. If You institute patent 80 | litigation against any entity (including a cross-claim or counterclaim in a 81 | lawsuit) alleging that the Work or a Contribution incorporated within the 82 | Work constitutes direct or contributory patent infringement, then any patent 83 | licenses granted to You under this License for that Work shall terminate as 84 | of the date such litigation is filed. 85 | 86 | 4. Redistribution. You may reproduce and distribute copies of the Work or 87 | Derivative Works thereof in any medium, with or without modifications, and in 88 | Source or Object form, provided that You meet the following conditions: 89 | 90 | (a) You must give any other recipients of the Work or Derivative Works a 91 | copy of this License; and 92 | 93 | (b) You must cause any modified files to carry prominent notices stating 94 | that You changed the files; and 95 | 96 | (c) You must retain, in the Source form of any Derivative Works that You 97 | distribute, all copyright, patent, trademark, and attribution notices from 98 | the Source form of the Work, excluding those notices that do not pertain to 99 | any part of the Derivative Works; and 100 | 101 | (d) If the Work includes a "NOTICE" text file as part of its distribution, 102 | then any Derivative Works that You distribute must include a readable copy 103 | of the attribution notices contained within such NOTICE file, excluding 104 | those notices that do not pertain to any part of the Derivative Works, in at 105 | least one of the following places: within a NOTICE text file distributed as 106 | part of the Derivative Works; within the Source form or documentation, if 107 | provided along with the Derivative Works; or, within a display generated by 108 | the Derivative Works, if and wherever such third-party notices normally 109 | appear. The contents of the NOTICE file are for informational purposes only 110 | and do not modify the License. You may add Your own attribution notices 111 | within Derivative Works that You distribute, alongside or as an addendum to 112 | the NOTICE text from the Work, provided that such additional attribution 113 | notices cannot be construed as modifying the License. 114 | 115 | You may add Your own copyright statement to Your modifications and may 116 | provide additional or different license terms and conditions for use, 117 | reproduction, or distribution of Your modifications, or for any such 118 | Derivative Works as a whole, provided Your use, reproduction, and 119 | distribution of the Work otherwise complies with the conditions stated in 120 | this License. 121 | 122 | 5. Submission of Contributions. Unless You explicitly state otherwise, any 123 | Contribution intentionally submitted for inclusion in the Work by You to the 124 | Licensor shall be under the terms and conditions of this License, without any 125 | additional terms or conditions. Notwithstanding the above, nothing herein 126 | shall supersede or modify the terms of any separate license agreement you may 127 | have executed with Licensor regarding such Contributions. 128 | 129 | 6. Trademarks. This License does not grant permission to use the trade names, 130 | trademarks, service marks, or product names of the Licensor, except as 131 | required for reasonable and customary use in describing the origin of the 132 | Work and reproducing the content of the NOTICE file. 133 | 134 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in 135 | writing, Licensor provides the Work (and each Contributor provides its 136 | Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 137 | KIND, either express or implied, including, without limitation, any 138 | warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or 139 | FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining 140 | the appropriateness of using or redistributing the Work and assume any risks 141 | associated with Your exercise of permissions under this License. 142 | 143 | 8. Limitation of Liability. In no event and under no legal theory, whether in 144 | tort (including negligence), contract, or otherwise, unless required by 145 | applicable law (such as deliberate and grossly negligent acts) or agreed to 146 | in writing, shall any Contributor be liable to You for damages, including any 147 | direct, indirect, special, incidental, or consequential damages of any 148 | character arising as a result of this License or out of the use or inability 149 | to use the Work (including but not limited to damages for loss of goodwill, 150 | work stoppage, computer failure or malfunction, or any and all other 151 | commercial damages or losses), even if such Contributor has been advised of 152 | the possibility of such damages. 153 | 154 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or 155 | Derivative Works thereof, You may choose to offer, and charge a fee for, 156 | acceptance of support, warranty, indemnity, or other liability obligations 157 | and/or rights consistent with this License. However, in accepting such 158 | obligations, You may act only on Your own behalf and on Your sole 159 | responsibility, not on behalf of any other Contributor, and only if You agree 160 | to indemnify, defend, and hold each Contributor harmless for any liability 161 | incurred by, or claims asserted against, such Contributor by reason of your 162 | accepting any such warranty or additional liability. 163 | 164 | END OF TERMS AND CONDITIONS 165 | 166 | APPENDIX: How to apply the Apache License to your work. 167 | 168 | To apply the Apache License to your work, attach the following 169 | boilerplate notice, with the fields enclosed by brackets "[]" 170 | replaced with your own identifying information. (Don't include 171 | the brackets!) The text should be enclosed in the appropriate 172 | comment syntax for the file format. We also recommend that a 173 | file or class name and description of purpose be included on the 174 | same "printed page" as the copyright notice for easier 175 | identification within third-party archives. 176 | 177 | Copyright [2020][thebyteavenue.com] 178 | 179 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 180 | this file except in compliance with the License. You may obtain a copy of the 181 | License at 182 | 183 | http://www.apache.org/licenses/LICENSE-2.0 184 | 185 | Unless required by applicable law or agreed to in writing, software distributed 186 | under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 187 | CONDITIONS OF ANY KIND, either express or implied. See the License for the 188 | specific language governing permissions and limitations under the License. 189 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Table of contents 2 | 3 | - Features 4 | - Installation 5 | - Prerequisities 6 | - Commands 7 | - Resources 8 | - Usage 9 | - Contributing 10 | - Credits 11 | - License 12 | 13 | # Features 14 | 15 | - `Express` app optimized to make better APIs 16 | - Changed structure to fit the API only use case 17 | - Removed `view` and `public` folder 18 | - Added error handling without html/templating engines 19 | - Added test route to understand the file structure and code splitting 20 | - Database connection using `mongoose`, based on environment (production 21 | ready) 22 | - Environment variable to help you control the app environment using `dotenv` 23 | - `Swagger` for API documentation 24 | - Pre-configured `husky` to run `eslint` and `prettier` on precommit hook, 25 | helps maintain best practices 26 | - Automatic versioning for apps on git push, using `yarn` 27 | - Tests pre-configured using `mocha` and `chai` 28 | 29 | # Installation 30 | 31 | #### Prerequisites 32 | 33 | - yarn 34 | - nodejs 35 | - mongodb local server or remote server url 36 | 37 | #### Follow these steps to get your app up and running within minutes 38 | 39 | - Click on `Use this template`, create your repo and clone it into your local 40 | machine 41 | - Upgrade all the dependencies and their version 42 | ``` 43 | yarn upgrade --latest 44 | ``` 45 | - Install all the dependencies 46 | ``` 47 | yarn install 48 | ``` 49 | - Add `.env` file and copy variables from `.env.sample` file, add your own 50 | values 51 | ``` 52 | touch .env 53 | cp .env.sample .env 54 | ``` 55 | - Replace `your_app_name` in `./bin/www` and `package.json`, essentially you 56 | might want to customise the `package.json` 57 | - Run the app 58 | ``` 59 | yarn start 60 | ``` 61 | - Go to localhost: or [localhost:3000](http://localhost:3000) 62 | - You can check the api documentation here - 63 | localhost:/swagger/api-docs or 64 | [localhost:3000/swagger/api-docs](http://localhost:3000/swagger/api-docs) 65 | 66 | #### Commands 67 | 68 | - To start the app 69 | ``` 70 | yarn start 71 | ``` 72 | - To test the app 73 | ``` 74 | yarn test 75 | ``` 76 | - To publish/push to github 77 | ``` 78 | yarn release:[patch|minor|major] 79 | ``` 80 | - use `patch`: when your are fixing an issue with is very small and 81 | doesn't make major changes in logic and structure of the code. 82 | - use `minor`: when you add/update any feature and update the logic of the 83 | code. 84 | - use `major`: when a major change is being released, something that is 85 | going to make a difference. 86 | 87 | #### Resources 88 | 89 | - Yarn: 90 | - [Documentation](https://classic.yarnpkg.com/en/docs/) 91 | - GitHub: 92 | - [Documentation](https://docs.github.com/en/github) 93 | - Swagger : 94 | - [Specifications](https://swagger.io/specification/) 95 | - [Editor](https://editor.swagger.io/) 96 | 97 | # Usage 98 | 99 | After you have the project up and running you can play around with almost any 100 | file. 101 | 102 | - Customize `./src/docs/swagger.yml` file - pre development, during 103 | development or post development 104 | - Update the `.eslintrc`, `.prettierrc`, `.prettierignore` and 105 | `.lint-staged.config.js` file based on your usecase and company policies 106 | - Add/remove variables into `.env` or `.env.sample` 107 | - Remove `./docs` and `./_config.yml` if you don't want to use ghpages 108 | 109 | # Contributing 110 | 111 | Please make use of the ISSUE_TEMPLATES for opening issues and making PRs 112 | 113 | # Credits 114 | 115 | This project was bootstraped by 116 | [@rajchandra3](https://github.com/rajchandra3). 117 | For contributions please feel free to make a PR. 118 | 119 | # License 120 | 121 | [Apache 2.0](http://www.apache.org/licenses/LICENSE-2.0) 122 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman 2 | title: A Template for NodeJs API server 3 | description: 4 | Spin up a nodejs server ready to be deployed in production within a minute 5 | -------------------------------------------------------------------------------- /app.js: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import cookieParser from 'cookie-parser'; 3 | import logger from 'morgan'; 4 | 5 | import './config.js'; // why? see here - https://www.npmjs.com/package/dotenv#how-do-i-use-dotenv-with-import- 6 | 7 | import connect from './src/components/db/setup.js'; 8 | import userRouter from './src/components/user/index.js'; 9 | import swaggerRouter from './src/docs/index.js'; 10 | 11 | // connect to db 12 | connect(); 13 | const app = express(); 14 | 15 | app.use(logger('dev')); 16 | app.use(express.json()); 17 | app.use(express.urlencoded({ extended: false })); 18 | app.use(cookieParser()); 19 | 20 | app.use('/', userRouter); 21 | app.use('/swagger', swaggerRouter); 22 | 23 | // error handler 24 | // catch 404 and forward to error handler 25 | app.use((req, res, next) => { 26 | const err = new Error('Not Found'); 27 | err.status = 404; 28 | next(err); 29 | }); 30 | 31 | app.use((err, req, res, next) => { 32 | // set locals, only providing error in development 33 | res.locals.message = err.message; 34 | res.locals.error = req.app.get('env') === 'development' ? err : {}; 35 | 36 | // render the error page 37 | if (!process.env.NODE_ENV) { 38 | console.log(err); 39 | } 40 | res.status(err.status || 500).send({ 41 | error: true, 42 | message: err.message, 43 | error_detail: { 44 | message: err.message, 45 | code: err.status, 46 | }, 47 | }); 48 | next(); 49 | }); 50 | 51 | export default app; 52 | -------------------------------------------------------------------------------- /bin/www.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /** 4 | * Module dependencies. 5 | */ 6 | import app from '../app.js'; 7 | import debug from 'debug'; 8 | import http from 'http'; 9 | import { hostname } from 'os'; 10 | /** 11 | * Get port from environment and store in Express. 12 | */ 13 | 14 | const port = normalizePort(process.env.PORT || '3000'); 15 | app.set('port', port); 16 | 17 | /** 18 | * Create HTTP server. 19 | */ 20 | 21 | const server = http.createServer(app); 22 | 23 | /** 24 | * Listen on provided port, on all network interfaces. 25 | */ 26 | 27 | server.listen(port); 28 | server.on('error', onError); 29 | server.on('listening', onListening); 30 | 31 | /** 32 | * Normalize a port into a number, string, or false. 33 | */ 34 | 35 | function normalizePort(val) { 36 | const port = parseInt(val, 10); 37 | 38 | if (isNaN(port)) { 39 | // named pipe 40 | return val; 41 | } 42 | 43 | if (port >= 0) { 44 | // port number 45 | return port; 46 | } 47 | 48 | return false; 49 | } 50 | 51 | /** 52 | * Event listener for HTTP server "error" event. 53 | */ 54 | 55 | function onError(error) { 56 | if (error.syscall !== 'listen') { 57 | throw error; 58 | } 59 | 60 | var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; 61 | 62 | // handle specific listen errors with friendly messages 63 | switch (error.code) { 64 | case 'EACCES': 65 | console.error(bind + ' requires elevated privileges'); 66 | process.exit(1); 67 | break; 68 | case 'EADDRINUSE': 69 | console.error(bind + ' is already in use'); 70 | process.exit(1); 71 | break; 72 | default: 73 | throw error; 74 | } 75 | } 76 | 77 | /** 78 | * Event listener for HTTP server "listening" event. 79 | */ 80 | 81 | function onListening() { 82 | const addr = server.address(); 83 | const bind = 84 | typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; 85 | debug('Listening on ' + bind); 86 | console.log( 87 | `App is up and running on ${bind}, click here - http://${hostname}:${port}`, 88 | ); 89 | } 90 | -------------------------------------------------------------------------------- /config.js: -------------------------------------------------------------------------------- 1 | import dotenv from 'dotenv'; 2 | 3 | dotenv.config({ silent: true }); 4 | 5 | // use this file for exporting any other config 6 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | #### Prerequisites 2 | 3 | - yarn 4 | - nodejs 5 | - mongodb local server or remote server url 6 | 7 | #### Available Commands 8 | 9 | - To start the app 10 | ``` 11 | yarn start 12 | ``` 13 | - To test the app 14 | ``` 15 | yarn test 16 | ``` 17 | - To publish/push to github 18 | ``` 19 | yarn release:[patch|minor|major] 20 | ``` 21 | - use `patch`: when your are fixing an issue with is very small and 22 | doesn't make major changes in logic and structure of the code. 23 | - use `minor`: when you add/update any feature and update the logic of the 24 | code. 25 | - use `major`: when a major change is being released, something that is 26 | going to make a difference. 27 | 28 | #### Getting started 29 | 30 | - Clone this repo 31 | - Upgrade all the dependencies and their version 32 | ``` 33 | yarn upgrade --latest 34 | ``` 35 | - Install all the dependencies 36 | ``` 37 | yarn install 38 | ``` 39 | - Add `.env` file and copy variables from `.env.sample` file, add your own 40 | values 41 | ``` 42 | touch .env 43 | cp .env.sample .env 44 | ``` 45 | - Replace `your_app_name` in `./bin/www` and `package.json`, essentially you 46 | might want to customise the `package.json` 47 | - Run the app 48 | ``` 49 | yarn start 50 | ``` 51 | - Go to localhost: or [localhost:3000](http://localhost:3000) 52 | - You can check the api documentation here - 53 | localhost:/swagger/api-docs or 54 | [localhost:3000/swagger/api-docs](http://localhost:3000/swagger/api-docs) 55 | 56 | * Further reading 57 | - Add your own git 58 | ``` 59 | rm -rf .git 60 | git init 61 | ``` 62 | - Customize `./src/docs/swagger.yml` file 63 | 64 | #### On Commit 65 | 66 | This is what happens under the hood: 67 | 68 | - git add . 69 | - git commit -u 70 | - runs tests 71 | - does linting 72 | - updates version 73 | - git push 74 | 75 | # Resources 76 | 77 | - Yarn: 78 | - [Documentation](https://classic.yarnpkg.com/en/docs/) 79 | - GitHub: 80 | - [Documentation](https://docs.github.com/en/github) 81 | - Swagger : 82 | - [Specifications](https://swagger.io/specification/) 83 | - [Editor](https://editor.swagger.io/) 84 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "your_app_name", 3 | "description": "A quickstart nodejs app with dotenv, mongodb(mongoose), automatic linting using husky, eslint and prettier inetgration.", 4 | "version": "0.0.8", 5 | "private": false, 6 | "license": "Apache-2.0", 7 | "type": "module", 8 | "scripts": { 9 | "precommit": "lint-staged", 10 | "start": "node ./bin/www", 11 | "watch:dev": "nodemon node ./bin/www", 12 | "test": "APP_ENV=development mocha --exit --timeout 10000", 13 | "release:patch": "yarn version --patch", 14 | "release:minor": "yarn version --minor", 15 | "release:major": "yarn version --major", 16 | "preversion": "yarn test && git add . && git commit -u", 17 | "postversion": "git push" 18 | }, 19 | "husky": { 20 | "hooks": { 21 | "pre-commit": "yarn precommit" 22 | } 23 | }, 24 | "dependencies": { 25 | "cookie-parser": "~1.4.4", 26 | "debug": "~2.6.9", 27 | "dotenv": "^8.2.0", 28 | "express": "~4.16.1", 29 | "mongoose": "^5.9.13", 30 | "morgan": "~1.9.1", 31 | "shortid": "^2.2.15", 32 | "swagger-ui-express": "^4.1.4", 33 | "yamljs": "^0.3.0" 34 | }, 35 | "devDependencies": { 36 | "chai": "^4.2.0", 37 | "chai-http": "^4.3.0", 38 | "eslint": "^7.0.0", 39 | "eslint-config-airbnb-base": "^14.1.0", 40 | "eslint-config-prettier": "^6.11.0", 41 | "eslint-plugin-import": "^2.20.2", 42 | "eslint-plugin-prettier": "^3.1.3", 43 | "husky": "^4.2.5", 44 | "lint-staged": "^10.2.2", 45 | "mocha": "^7.1.2", 46 | "prettier": "^2.0.5" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/components/db/setup.js: -------------------------------------------------------------------------------- 1 | import mongoose from 'mongoose'; 2 | 3 | mongoose.set('useCreateIndex', true); 4 | 5 | const production = process.env.APP_ENV === 'production'; 6 | const dbUrl = production 7 | ? process.env.ATLAS_URL_PRODUCTION 8 | : process.env.ATLAS_URL_TEST; 9 | const connect = () => { 10 | // CONNECTING TO MONGODB ON START 11 | mongoose.connect( 12 | dbUrl, 13 | { 14 | useNewUrlParser: true, 15 | retryWrites: false, 16 | useUnifiedTopology: true, 17 | }, 18 | (e) => { 19 | if (e) { 20 | console.log('e', e); 21 | process.exit(1); 22 | } else if (!production) { 23 | console.log('Database ready to use.', dbUrl); 24 | } else if (process.env.APP_ENV === 'production') { 25 | console.log('Database ready to use.'); 26 | } 27 | }, 28 | ); 29 | }; 30 | 31 | export default connect; 32 | -------------------------------------------------------------------------------- /src/components/user/controller.js: -------------------------------------------------------------------------------- 1 | const getStarted = () => { 2 | return { 3 | error: false, 4 | message: `Congratulations! We were able to fetch your app data.`, 5 | }; 6 | }; 7 | 8 | export default getStarted; 9 | -------------------------------------------------------------------------------- /src/components/user/index.js: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import getStarted from './controller.js'; 3 | 4 | const userRouter = express.Router(); 5 | 6 | // template route 7 | userRouter.get('/', (req, res) => { 8 | res.status(200).send(getStarted()); 9 | }); 10 | 11 | export default userRouter; 12 | -------------------------------------------------------------------------------- /src/components/user/index.spec.js: -------------------------------------------------------------------------------- 1 | // Require the dev-dependencies 2 | import chai from 'chai'; 3 | import chaiHttp from 'chai-http'; 4 | import app from '../../../app.js'; 5 | 6 | const { expect } = chai; 7 | 8 | chai.use(chaiHttp); 9 | 10 | describe('User', () => { 11 | it('It should not have error as false', (done) => { 12 | const url = '/'; 13 | chai.request(app) 14 | .get(url) 15 | .end((err, res) => { 16 | expect(res.body.error).to.be.false; 17 | expect(res).to.have.status(200); 18 | done(); 19 | }); 20 | }); 21 | }); 22 | -------------------------------------------------------------------------------- /src/components/user/validator.js: -------------------------------------------------------------------------------- 1 | // validate something here, 2 | // like request using express validator or using your own code 3 | -------------------------------------------------------------------------------- /src/docs/index.js: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import swaggerUI from 'swagger-ui-express'; 3 | import YAML from 'yamljs'; 4 | 5 | const swaggerRouter = express.Router(); 6 | 7 | const swaggerDocument = YAML.load('./src/docs/swagger.yml'); 8 | 9 | swaggerRouter.use('/api-docs', swaggerUI.serve); 10 | swaggerRouter.get('/api-docs', swaggerUI.setup(swaggerDocument)); 11 | 12 | export default swaggerRouter; 13 | -------------------------------------------------------------------------------- /src/docs/swagger.yml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.1 2 | info: 3 | title: Template for nodejs 4 | description: description 5 | termsOfService: https://localhost:8059/terms 6 | contact: 7 | email: example@email.com 8 | license: 9 | name: Apache 2.0 10 | url: http://www.apache.org/licenses/LICENSE-2.0.html 11 | version: 1.0.0 12 | externalDocs: 13 | description: Find out more about Swagger 14 | url: http://swagger.io 15 | servers: 16 | - url: http://localhost:8059/ 17 | tags: 18 | - name: user 19 | description: information about user 20 | paths: 21 | /: 22 | get: 23 | tags: 24 | - user 25 | summary: verify whether the app is working 26 | description: this route gives you information about the app 27 | operationId: getstarted 28 | responses: 29 | 200: 30 | description: Operation unsuccessfull 31 | content: 32 | application/json: 33 | schema: 34 | type: object 35 | properties: 36 | error: 37 | type: string 38 | example: 'true' 39 | message: 40 | type: string 41 | example: Something went wrong! 42 | payload: 43 | type: object 44 | properties: {} 45 | example: {} 46 | 201: 47 | description: Operation Successfull, resource created 48 | content: 49 | application/json: 50 | schema: 51 | type: object 52 | properties: 53 | error: 54 | type: string 55 | example: 'false' 56 | message: 57 | type: string 58 | example: Congratulations! We were able to 59 | fetch your app data. 60 | payload: 61 | type: object 62 | example: {} 63 | 400: 64 | description: Invalid input 65 | content: 66 | application/json: 67 | schema: 68 | $ref: '#/components/schemas/ApiErrorResponse' 69 | components: 70 | schemas: 71 | UserCredentials: 72 | type: object 73 | properties: 74 | first_name: 75 | type: string 76 | example: John 77 | last_name: 78 | type: string 79 | example: Snow 80 | email: 81 | type: string 82 | example: john.snow@got.us 83 | password: 84 | type: string 85 | example: gotis4<34 86 | confirm_password: 87 | type: string 88 | example: gotis4<34 89 | google_recaptcha: 90 | type: string 91 | User: 92 | type: object 93 | properties: 94 | uid: 95 | type: string 96 | example: hstnwi6wbs5g 97 | usename: 98 | type: string 99 | example: johnsnow 100 | first_name: 101 | type: string 102 | example: John 103 | last_name: 104 | type: string 105 | example: Snow 106 | about: 107 | type: string 108 | example: I am a Programmer 109 | picture: 110 | type: string 111 | example: https://images5.alphacoders.com/415/thumb-1920-415296.jpg 112 | ApiErrorResponse: 113 | type: object 114 | properties: 115 | error: 116 | type: boolean 117 | example: true 118 | message: 119 | type: string 120 | example: Your entries are not valid! 121 | payload: 122 | type: object 123 | properties: {} 124 | example: {} 125 | ApiSuccessResponse: 126 | type: object 127 | properties: 128 | error: 129 | type: boolean 130 | example: false 131 | message: 132 | type: string 133 | example: Your account information was updated successfully! 134 | payload: 135 | type: object 136 | properties: {} 137 | example: '#/definations/User' 138 | securitySchemes: 139 | petstore_auth: 140 | type: oauth2 141 | flows: 142 | implicit: 143 | authorizationUrl: http://petstore.swagger.io/oauth/dialog 144 | scopes: 145 | write:pets: modify pets in your account 146 | read:pets: read your pets 147 | api_key: 148 | type: apiKey 149 | name: api_key 150 | in: header 151 | -------------------------------------------------------------------------------- /src/schemas/user.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/byteavenueHQ/template-nodejs-api/ead06a1f47a93ed2f52520c1a3548c19bffa5a62/src/schemas/user.js -------------------------------------------------------------------------------- /test/index.js: -------------------------------------------------------------------------------- 1 | // require all index.spec.js files 2 | import '../src/components/user/index.spec.js'; 3 | --------------------------------------------------------------------------------