create-nodejs-express-starter 1.7.0

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.
Files changed (70) hide show
  1. package/.dockerignore +3 -0
  2. package/.editorconfig +9 -0
  3. package/.env.example +22 -0
  4. package/.eslintignore +2 -0
  5. package/.eslintrc.json +32 -0
  6. package/.gitignore +14 -0
  7. package/.prettierignore +3 -0
  8. package/.prettierrc.json +4 -0
  9. package/Dockerfile +15 -0
  10. package/LICENSE +21 -0
  11. package/README.md +440 -0
  12. package/bin/createNodejsApp.js +106 -0
  13. package/docker-compose.dev.yml +4 -0
  14. package/docker-compose.prod.yml +4 -0
  15. package/docker-compose.test.yml +4 -0
  16. package/docker-compose.yml +30 -0
  17. package/jest.config.js +9 -0
  18. package/package.json +117 -0
  19. package/src/app.js +82 -0
  20. package/src/config/config.js +64 -0
  21. package/src/config/logger.js +26 -0
  22. package/src/config/morgan.js +25 -0
  23. package/src/config/passport.js +30 -0
  24. package/src/config/roles.js +12 -0
  25. package/src/config/tokens.js +10 -0
  26. package/src/controllers/auth.controller.js +59 -0
  27. package/src/controllers/index.js +2 -0
  28. package/src/controllers/user.controller.js +43 -0
  29. package/src/docs/components.yml +92 -0
  30. package/src/docs/swaggerDef.js +21 -0
  31. package/src/index.js +57 -0
  32. package/src/middlewares/auth.js +33 -0
  33. package/src/middlewares/error.js +47 -0
  34. package/src/middlewares/rateLimiter.js +11 -0
  35. package/src/middlewares/requestId.js +14 -0
  36. package/src/middlewares/validate.js +21 -0
  37. package/src/models/index.js +2 -0
  38. package/src/models/plugins/index.js +2 -0
  39. package/src/models/plugins/paginate.plugin.js +70 -0
  40. package/src/models/plugins/toJSON.plugin.js +43 -0
  41. package/src/models/token.model.js +44 -0
  42. package/src/models/user.model.js +91 -0
  43. package/src/routes/v1/auth.route.js +291 -0
  44. package/src/routes/v1/docs.route.js +21 -0
  45. package/src/routes/v1/health.route.js +43 -0
  46. package/src/routes/v1/index.js +39 -0
  47. package/src/routes/v1/user.route.js +252 -0
  48. package/src/services/auth.service.js +99 -0
  49. package/src/services/email.service.js +63 -0
  50. package/src/services/index.js +4 -0
  51. package/src/services/token.service.js +123 -0
  52. package/src/services/user.service.js +89 -0
  53. package/src/utils/ApiError.js +14 -0
  54. package/src/utils/catchAsync.js +5 -0
  55. package/src/utils/pick.js +17 -0
  56. package/src/validations/auth.validation.js +60 -0
  57. package/src/validations/custom.validation.js +21 -0
  58. package/src/validations/index.js +2 -0
  59. package/src/validations/user.validation.js +54 -0
  60. package/tests/fixtures/token.fixture.js +14 -0
  61. package/tests/fixtures/user.fixture.js +46 -0
  62. package/tests/integration/auth.test.js +587 -0
  63. package/tests/integration/docs.test.js +14 -0
  64. package/tests/integration/health.test.js +32 -0
  65. package/tests/integration/user.test.js +625 -0
  66. package/tests/unit/middlewares/error.test.js +168 -0
  67. package/tests/unit/models/plugins/paginate.plugin.test.js +61 -0
  68. package/tests/unit/models/plugins/toJSON.plugin.test.js +89 -0
  69. package/tests/unit/models/user.model.test.js +57 -0
  70. package/tests/utils/setupTestDB.js +18 -0
package/.dockerignore ADDED
@@ -0,0 +1,3 @@
1
+ node_modules
2
+ .git
3
+ .gitignore
package/.editorconfig ADDED
@@ -0,0 +1,9 @@
1
+ root = true
2
+
3
+ [*]
4
+ indent_style = space
5
+ indent_size = 2
6
+ end_of_line = lf
7
+ charset = utf-8
8
+ trim_trailing_whitespace = true
9
+ insert_final_newline = true
package/.env.example ADDED
@@ -0,0 +1,22 @@
1
+ # Application
2
+ NODE_ENV=development
3
+ PORT=3000
4
+ LOG_LEVEL=info
5
+ CORS_ORIGIN=*
6
+
7
+ # Database
8
+ MONGODB_URL=mongodb://127.0.0.1:27017/node-boilerplate
9
+
10
+ # JWT
11
+ JWT_SECRET=your-super-secret-key-change-in-production
12
+ JWT_ACCESS_EXPIRATION_MINUTES=30
13
+ JWT_REFRESH_EXPIRATION_DAYS=30
14
+ JWT_RESET_PASSWORD_EXPIRATION_MINUTES=10
15
+ JWT_VERIFY_EMAIL_EXPIRATION_MINUTES=10
16
+
17
+ # SMTP (optional - for email verification and password reset)
18
+ SMTP_HOST=email-server
19
+ SMTP_PORT=587
20
+ SMTP_USERNAME=email-server-username
21
+ SMTP_PASSWORD=email-server-password
22
+ EMAIL_FROM=support@yourapp.com
package/.eslintignore ADDED
@@ -0,0 +1,2 @@
1
+ node_modules
2
+ bin
package/.eslintrc.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "env": {
3
+ "node": true,
4
+ "jest": true
5
+ },
6
+ "extends": ["airbnb-base", "plugin:jest/recommended", "plugin:prettier/recommended"],
7
+ "plugins": ["jest", "security", "prettier"],
8
+ "parserOptions": {
9
+ "ecmaVersion": 2018
10
+ },
11
+ "rules": {
12
+ "no-console": "error",
13
+ "func-names": "off",
14
+ "no-underscore-dangle": "off",
15
+ "consistent-return": "off",
16
+ "jest/expect-expect": "off",
17
+ "security/detect-buffer-noassert": "warn",
18
+ "security/detect-child-process": "warn",
19
+ "security/detect-disable-mustache-escape": "warn",
20
+ "security/detect-eval-with-expression": "warn",
21
+ "security/detect-new-buffer": "warn",
22
+ "security/detect-no-csrf-before-method-override": "warn",
23
+ "security/detect-non-literal-fs-filename": "warn",
24
+ "security/detect-non-literal-regexp": "warn",
25
+ "security/detect-non-literal-require": "warn",
26
+ "security/detect-object-injection": "off",
27
+ "security/detect-possible-timing-attacks": "warn",
28
+ "security/detect-pseudoRandomBytes": "warn",
29
+ "security/detect-unsafe-regex": "warn",
30
+ "security/detect-bidi-characters": "warn"
31
+ }
32
+ }
package/.gitignore ADDED
@@ -0,0 +1,14 @@
1
+ # Dependencies
2
+ node_modules
3
+
4
+ # yarn error logs
5
+ yarn-error.log
6
+
7
+ # Environment varibales
8
+ .env*
9
+ !.env*.example
10
+
11
+ # Code coverage
12
+ coverage
13
+
14
+ meow
@@ -0,0 +1,3 @@
1
+ node_modules
2
+ coverage
3
+
@@ -0,0 +1,4 @@
1
+ {
2
+ "singleQuote": true,
3
+ "printWidth": 125
4
+ }
package/Dockerfile ADDED
@@ -0,0 +1,15 @@
1
+ FROM node:alpine
2
+
3
+ RUN mkdir -p /usr/src/node-app && chown -R node:node /usr/src/node-app
4
+
5
+ WORKDIR /usr/src/node-app
6
+
7
+ COPY package.json package-lock.json ./
8
+
9
+ USER node
10
+
11
+ RUN npm ci
12
+
13
+ COPY --chown=node:node . .
14
+
15
+ EXPOSE 3000
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2019 Hagop Jamkojian
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,440 @@
1
+ # RESTful API Node Server Boilerplate
2
+
3
+ [![Coverage Status](https://coveralls.io/repos/github/Ahlyab/express-backend-starter-js/badge.svg?branch=main)](https://coveralls.io/github/Ahlyab/express-backend-starter-js?branch=main)
4
+ [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)
5
+
6
+ A boilerplate/starter project for quickly building RESTful APIs using Node.js, Express, and Mongoose.
7
+
8
+ By running a single command, you will get a production-ready Node.js app installed and fully configured on your machine. The app comes with many built-in features, such as authentication using JWT, request validation, unit and integration tests, continuous integration, docker support, API documentation, pagination, etc. For more details, check the features list below.
9
+
10
+ ## Quick Start
11
+
12
+ To create and initialize a new project in one command:
13
+
14
+ ```bash
15
+ npx nodejs-express-starter <project-name>
16
+ ```
17
+
18
+ Or:
19
+
20
+ ```bash
21
+ npm init nodejs-express-starter <project-name>
22
+ ```
23
+
24
+ This will create a new folder with the project name, copy the template, install dependencies (`npm install`), and set up `.env` from `.env.example`. Then:
25
+
26
+ ```bash
27
+ cd <project-name>
28
+ # edit .env if needed
29
+ npm run dev
30
+ ```
31
+
32
+ ## Manual Installation
33
+
34
+ If you prefer to clone and set up manually:
35
+
36
+ Clone the repo:
37
+
38
+ ```bash
39
+ git clone --depth 1 https://github.com/Ahlyab/express-backend-starter-js.git
40
+ cd express-backend-starter-js
41
+ npx rimraf ./.git
42
+ ```
43
+
44
+ Install the dependencies:
45
+
46
+ ```bash
47
+ npm install
48
+ ```
49
+
50
+ Set the environment variables:
51
+
52
+ ```bash
53
+ cp .env.example .env
54
+
55
+ # open .env and modify the environment variables (if needed)
56
+ ```
57
+
58
+ ## Table of Contents
59
+
60
+ - [Features](#features)
61
+ - [Commands](#commands)
62
+ - [Environment Variables](#environment-variables)
63
+ - [Project Structure](#project-structure)
64
+ - [API Documentation](#api-documentation)
65
+ - [Error Handling](#error-handling)
66
+ - [Validation](#validation)
67
+ - [Authentication](#authentication)
68
+ - [Authorization](#authorization)
69
+ - [Logging](#logging)
70
+ - [Custom Mongoose Plugins](#custom-mongoose-plugins)
71
+ - [Linting](#linting)
72
+ - [Contributing](#contributing)
73
+
74
+ ## Features
75
+
76
+ - **NoSQL database**: [MongoDB](https://www.mongodb.com) object data modeling using [Mongoose](https://mongoosejs.com)
77
+ - **Authentication and authorization**: using [passport](http://www.passportjs.org)
78
+ - **Validation**: request data validation using [Joi](https://github.com/hapijs/joi)
79
+ - **Logging**: using [winston](https://github.com/winstonjs/winston) and [morgan](https://github.com/expressjs/morgan)
80
+ - **Testing**: unit and integration tests using [Jest](https://jestjs.io)
81
+ - **Error handling**: centralized error handling mechanism
82
+ - **API documentation**: with [swagger-jsdoc](https://github.com/Surnet/swagger-jsdoc) and [swagger-ui-express](https://github.com/scottie1984/swagger-ui-express)
83
+ - **Production start**: run with `node src/index.js` (add a process manager like PM2 or systemd if you need clustering)
84
+ - **Dependency management**: with [npm](https://www.npmjs.com)
85
+ - **Environment variables**: using [dotenv](https://github.com/motdotla/dotenv) and [cross-env](https://github.com/kentcdodds/cross-env#readme)
86
+ - **Security**: set security HTTP headers using [helmet](https://helmetjs.github.io)
87
+ - **Santizing**: sanitize request data against xss and query injection
88
+ - **CORS**: Cross-Origin Resource-Sharing enabled using [cors](https://github.com/expressjs/cors)
89
+ - **Compression**: gzip compression with [compression](https://github.com/expressjs/compression)
90
+ - **CI**: continuous integration with [Travis CI](https://travis-ci.org)
91
+ - **Docker support**
92
+ - **Code coverage**: reported to [Coveralls](https://coveralls.io) via GitHub Actions
93
+ - **Code quality**: with [Codacy](https://www.codacy.com)
94
+ - **Git hooks**: with [husky](https://github.com/typicode/husky) and [lint-staged](https://github.com/okonet/lint-staged)
95
+ - **Linting**: with [ESLint](https://eslint.org) and [Prettier](https://prettier.io)
96
+ - **Editor config**: consistent editor configuration using [EditorConfig](https://editorconfig.org)
97
+
98
+ ## Commands
99
+
100
+ Running locally:
101
+
102
+ ```bash
103
+ npm run dev
104
+ ```
105
+
106
+ Running in production:
107
+
108
+ ```bash
109
+ npm start
110
+ ```
111
+
112
+ Testing:
113
+
114
+ ```bash
115
+ # run all tests
116
+ npm test
117
+
118
+ # run all tests in watch mode
119
+ npm run test:watch
120
+
121
+ # run test coverage
122
+ npm run coverage
123
+ ```
124
+
125
+ Docker:
126
+
127
+ ```bash
128
+ # run docker container in development mode
129
+ npm run docker:dev
130
+
131
+ # run docker container in production mode
132
+ npm run docker:prod
133
+
134
+ # run all tests in a docker container
135
+ npm run docker:test
136
+ ```
137
+
138
+ Linting:
139
+
140
+ ```bash
141
+ # run ESLint
142
+ npm run lint
143
+
144
+ # fix ESLint errors
145
+ npm run lint:fix
146
+
147
+ # run prettier
148
+ npm run prettier
149
+
150
+ # fix prettier errors
151
+ npm run prettier:fix
152
+ ```
153
+
154
+ ## Environment Variables
155
+
156
+ Copy `.env.example` to `.env` and modify as needed. Required variables:
157
+
158
+ | Variable | Description | Default |
159
+ |----------|-------------|---------|
160
+ | NODE_ENV | Environment (development, test, production) | required |
161
+ | PORT | Server port | 3000 |
162
+ | LOG_LEVEL | Log level (error, warn, info, http, verbose, debug) | info |
163
+ | CORS_ORIGIN | Allowed CORS origins (comma-separated, use * for all) | * |
164
+ | MONGODB_URL | MongoDB connection URL | required |
165
+ | JWT_SECRET | JWT signing secret | required |
166
+ | JWT_ACCESS_EXPIRATION_MINUTES | Access token expiry | 30 |
167
+ | JWT_REFRESH_EXPIRATION_DAYS | Refresh token expiry | 30 |
168
+ | SMTP_* | Email configuration (optional, for verification/reset) | - |
169
+
170
+ ## Project Structure
171
+
172
+ ```
173
+ src\
174
+ |--config\ # Environment variables and configuration related things
175
+ |--controllers\ # Route controllers (controller layer)
176
+ |--docs\ # Swagger files
177
+ |--middlewares\ # Custom express middlewares
178
+ |--models\ # Mongoose models (data layer)
179
+ |--routes\ # Routes
180
+ |--services\ # Business logic (service layer)
181
+ |--utils\ # Utility classes and functions
182
+ |--validations\ # Request data validation schemas
183
+ |--app.js # Express app
184
+ |--index.js # App entry point
185
+ ```
186
+
187
+ ## API Documentation
188
+
189
+ To view the list of available APIs and their specifications, run the server and go to `http://localhost:3000/v1/docs` in your browser. This documentation page is automatically generated using the [swagger](https://swagger.io/) definitions written as comments in the route files.
190
+
191
+ ### API Endpoints
192
+
193
+ List of available routes:
194
+
195
+ **Health** (for load balancers, orchestration):\
196
+ `GET /health` - liveness check\
197
+ `GET /health/ready` - readiness check (includes DB status)
198
+
199
+ **Auth routes**:\
200
+ `POST /v1/auth/register` - register\
201
+ `POST /v1/auth/login` - login\
202
+ `POST /v1/auth/refresh-tokens` - refresh auth tokens\
203
+ `POST /v1/auth/forgot-password` - send reset password email\
204
+ `POST /v1/auth/reset-password` - reset password\
205
+ `POST /v1/auth/send-verification-email` - send verification email\
206
+ `POST /v1/auth/verify-email` - verify email
207
+
208
+ **User routes**:\
209
+ `POST /v1/users` - create a user\
210
+ `GET /v1/users` - get all users\
211
+ `GET /v1/users/:userId` - get user\
212
+ `PATCH /v1/users/:userId` - update user\
213
+ `DELETE /v1/users/:userId` - delete user
214
+
215
+ ## Error Handling
216
+
217
+ The app has a centralized error handling mechanism.
218
+
219
+ Controllers should try to catch the errors and forward them to the error handling middleware (by calling `next(error)`). For convenience, you can also wrap the controller inside the catchAsync utility wrapper, which forwards the error.
220
+
221
+ ```javascript
222
+ const catchAsync = require('../utils/catchAsync');
223
+
224
+ const controller = catchAsync(async (req, res) => {
225
+ // this error will be forwarded to the error handling middleware
226
+ throw new Error('Something wrong happened');
227
+ });
228
+ ```
229
+
230
+ The error handling middleware sends an error response, which has the following format:
231
+
232
+ ```json
233
+ {
234
+ "code": 404,
235
+ "message": "Not found"
236
+ }
237
+ ```
238
+
239
+ When running in development mode, the error response also contains the error stack.
240
+
241
+ The app has a utility ApiError class to which you can attach a response code and a message, and then throw it from anywhere (catchAsync will catch it).
242
+
243
+ For example, if you are trying to get a user from the DB who is not found, and you want to send a 404 error, the code should look something like:
244
+
245
+ ```javascript
246
+ const httpStatus = require('http-status');
247
+ const ApiError = require('../utils/ApiError');
248
+ const User = require('../models/User');
249
+
250
+ const getUser = async (userId) => {
251
+ const user = await User.findById(userId);
252
+ if (!user) {
253
+ throw new ApiError(httpStatus.NOT_FOUND, 'User not found');
254
+ }
255
+ };
256
+ ```
257
+
258
+ ## Validation
259
+
260
+ Request data is validated using [Joi](https://joi.dev/). Check the [documentation](https://joi.dev/api/) for more details on how to write Joi validation schemas.
261
+
262
+ The validation schemas are defined in the `src/validations` directory and are used in the routes by providing them as parameters to the `validate` middleware.
263
+
264
+ ```javascript
265
+ const express = require('express');
266
+ const validate = require('../../middlewares/validate');
267
+ const userValidation = require('../../validations/user.validation');
268
+ const userController = require('../../controllers/user.controller');
269
+
270
+ const router = express.Router();
271
+
272
+ router.post('/users', validate(userValidation.createUser), userController.createUser);
273
+ ```
274
+
275
+ ## Authentication
276
+
277
+ To require authentication for certain routes, you can use the `auth` middleware.
278
+
279
+ ```javascript
280
+ const express = require('express');
281
+ const auth = require('../../middlewares/auth');
282
+ const userController = require('../../controllers/user.controller');
283
+
284
+ const router = express.Router();
285
+
286
+ router.post('/users', auth(), userController.createUser);
287
+ ```
288
+
289
+ These routes require a valid JWT access token in the Authorization request header using the Bearer schema. If the request does not contain a valid access token, an Unauthorized (401) error is thrown.
290
+
291
+ **Generating Access Tokens**:
292
+
293
+ An access token can be generated by making a successful call to the register (`POST /v1/auth/register`) or login (`POST /v1/auth/login`) endpoints. The response of these endpoints also contains refresh tokens (explained below).
294
+
295
+ An access token is valid for 30 minutes. You can modify this expiration time by changing the `JWT_ACCESS_EXPIRATION_MINUTES` environment variable in the .env file.
296
+
297
+ **Refreshing Access Tokens**:
298
+
299
+ After the access token expires, a new access token can be generated, by making a call to the refresh token endpoint (`POST /v1/auth/refresh-tokens`) and sending along a valid refresh token in the request body. This call returns a new access token and a new refresh token.
300
+
301
+ A refresh token is valid for 30 days. You can modify this expiration time by changing the `JWT_REFRESH_EXPIRATION_DAYS` environment variable in the .env file.
302
+
303
+ ## Authorization
304
+
305
+ The `auth` middleware can also be used to require certain rights/permissions to access a route.
306
+
307
+ ```javascript
308
+ const express = require('express');
309
+ const auth = require('../../middlewares/auth');
310
+ const userController = require('../../controllers/user.controller');
311
+
312
+ const router = express.Router();
313
+
314
+ router.post('/users', auth('manageUsers'), userController.createUser);
315
+ ```
316
+
317
+ In the example above, an authenticated user can access this route only if that user has the `manageUsers` permission.
318
+
319
+ The permissions are role-based. You can view the permissions/rights of each role in the `src/config/roles.js` file.
320
+
321
+ If the user making the request does not have the required permissions to access this route, a Forbidden (403) error is thrown.
322
+
323
+ ## Logging
324
+
325
+ Import the logger from `src/config/logger.js`. It is using the [Winston](https://github.com/winstonjs/winston) logging library.
326
+
327
+ Logging should be done according to the following severity levels (ascending order from most important to least important):
328
+
329
+ ```javascript
330
+ const logger = require('<path to src>/config/logger');
331
+
332
+ logger.error('message'); // level 0
333
+ logger.warn('message'); // level 1
334
+ logger.info('message'); // level 2
335
+ logger.http('message'); // level 3
336
+ logger.verbose('message'); // level 4
337
+ logger.debug('message'); // level 5
338
+ ```
339
+
340
+ In development mode, log messages of all severity levels will be printed to the console.
341
+
342
+ In production mode, only `info`, `warn`, and `error` logs will be printed to the console.\
343
+ It is up to the server (or process manager) to actually read them from the console and store them in log files.\
344
+ In production, ensure your process manager or environment captures stdout/stderr (e.g. Docker, systemd, or a logging service) so logs are stored as needed.
345
+
346
+ Note: API request information (request url, response code, timestamp, etc.) are also automatically logged (using [morgan](https://github.com/expressjs/morgan)).
347
+
348
+ ## Custom Mongoose Plugins
349
+
350
+ The app also contains 2 custom mongoose plugins that you can attach to any mongoose model schema. You can find the plugins in `src/models/plugins`.
351
+
352
+ ```javascript
353
+ const mongoose = require('mongoose');
354
+ const { toJSON, paginate } = require('./plugins');
355
+
356
+ const userSchema = mongoose.Schema(
357
+ {
358
+ /* schema definition here */
359
+ },
360
+ { timestamps: true }
361
+ );
362
+
363
+ userSchema.plugin(toJSON);
364
+ userSchema.plugin(paginate);
365
+
366
+ const User = mongoose.model('User', userSchema);
367
+ ```
368
+
369
+ ### toJSON
370
+
371
+ The toJSON plugin applies the following changes in the toJSON transform call:
372
+
373
+ - removes \_\_v, createdAt, updatedAt, and any schema path that has private: true
374
+ - replaces \_id with id
375
+
376
+ ### paginate
377
+
378
+ The paginate plugin adds the `paginate` static method to the mongoose schema.
379
+
380
+ Adding this plugin to the `User` model schema will allow you to do the following:
381
+
382
+ ```javascript
383
+ const queryUsers = async (filter, options) => {
384
+ const users = await User.paginate(filter, options);
385
+ return users;
386
+ };
387
+ ```
388
+
389
+ The `filter` param is a regular mongo filter.
390
+
391
+ The `options` param can have the following (optional) fields:
392
+
393
+ ```javascript
394
+ const options = {
395
+ sortBy: 'name:desc', // sort order
396
+ limit: 5, // maximum results per page
397
+ page: 2, // page number
398
+ };
399
+ ```
400
+
401
+ The plugin also supports sorting by multiple criteria (separated by a comma): `sortBy: name:desc,role:asc`
402
+
403
+ The `paginate` method returns a Promise, which fulfills with an object having the following properties:
404
+
405
+ ```json
406
+ {
407
+ "results": [],
408
+ "page": 2,
409
+ "limit": 5,
410
+ "totalPages": 10,
411
+ "totalResults": 48
412
+ }
413
+ ```
414
+
415
+ ## Linting
416
+
417
+ Linting is done using [ESLint](https://eslint.org/) and [Prettier](https://prettier.io).
418
+
419
+ In this app, ESLint is configured to follow the [Airbnb JavaScript style guide](https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb-base) with some modifications. It also extends [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) to turn off all rules that are unnecessary or might conflict with Prettier.
420
+
421
+ To modify the ESLint configuration, update the `.eslintrc.json` file. To modify the Prettier configuration, update the `.prettierrc.json` file.
422
+
423
+ To prevent a certain file or directory from being linted, add it to `.eslintignore` and `.prettierignore`.
424
+
425
+ To maintain a consistent coding style across different IDEs, the project contains `.editorconfig`
426
+
427
+ ## Contributing
428
+
429
+ Contributions are more than welcome! Please check out the [contributing guide](CONTRIBUTING.md).
430
+
431
+ ## Inspirations
432
+
433
+ - [hagopj13/node-express-boilerplate](https://github.com/hagopj13/node-express-boilerplate) – boilerplate this project is based on
434
+ - [danielfsousa/express-rest-es2017-boilerplate](https://github.com/danielfsousa/express-rest-es2017-boilerplate)
435
+ - [madhums/node-express-mongoose](https://github.com/madhums/node-express-mongoose)
436
+ - [kunalkapadia/express-mongoose-es6-rest-api](https://github.com/kunalkapadia/express-mongoose-es6-rest-api)
437
+
438
+ ## License
439
+
440
+ [MIT](LICENSE)
@@ -0,0 +1,106 @@
1
+ #!/usr/bin/env node
2
+
3
+ const path = require('path');
4
+ const fs = require('fs');
5
+ const { spawnSync } = require('child_process');
6
+
7
+ const EXCLUDE_DIRS = new Set(['node_modules', '.git', 'coverage', 'bin']);
8
+ const EXCLUDE_FILES = new Set(['.env']);
9
+
10
+ function copyRecursive(src, dest, templateRoot, excludeDirName) {
11
+ const stat = fs.statSync(src);
12
+ const basename = path.basename(src);
13
+
14
+ if (EXCLUDE_DIRS.has(basename)) return;
15
+ if (excludeDirName && basename === excludeDirName) return;
16
+ if (basename === '.env' || (basename.startsWith('.env') && !basename.endsWith('.example'))) return;
17
+
18
+ if (stat.isDirectory()) {
19
+ fs.mkdirSync(dest, { recursive: true });
20
+ for (const name of fs.readdirSync(src)) {
21
+ copyRecursive(path.join(src, name), path.join(dest, name), templateRoot, excludeDirName);
22
+ }
23
+ } else {
24
+ fs.copyFileSync(src, dest);
25
+ }
26
+ }
27
+
28
+ function main() {
29
+ const projectName = process.argv[2];
30
+ if (!projectName) {
31
+ console.error('Usage: npx nodejs-express-starter <project-name>');
32
+ console.error('Example: npx nodejs-express-starter my-api');
33
+ process.exit(1);
34
+ }
35
+
36
+ const templateRoot = path.resolve(__dirname, '..');
37
+ const targetDir = path.resolve(process.cwd(), projectName);
38
+
39
+ if (fs.existsSync(targetDir)) {
40
+ console.error(`Error: "${projectName}" already exists in this directory.`);
41
+ process.exit(1);
42
+ }
43
+
44
+ console.log(`Creating a new Express app in ./${projectName}...`);
45
+
46
+ try {
47
+ fs.mkdirSync(targetDir, { recursive: true });
48
+ } catch (err) {
49
+ if (err.code === 'EACCES') {
50
+ console.error(`Error: Permission denied creating folder at ${targetDir}`);
51
+ console.error('Run the command from a directory you can write to (e.g. your home or Desktop):');
52
+ console.error(` cd ~/Desktop && npx nodejs-express-starter ${projectName}`);
53
+ } else {
54
+ console.error(`Error: ${err.message}`);
55
+ }
56
+ process.exit(1);
57
+ }
58
+
59
+ const entries = fs.readdirSync(templateRoot, { withFileTypes: true });
60
+ for (const entry of entries) {
61
+ if (entry.name === 'bin') continue;
62
+ if (entry.name === projectName) continue; // avoid copying a same-named folder (e.g. from a previous run) into itself
63
+ const srcPath = path.join(templateRoot, entry.name);
64
+ const destPath = path.join(targetDir, entry.name);
65
+ if (entry.isDirectory()) {
66
+ if (!EXCLUDE_DIRS.has(entry.name)) {
67
+ copyRecursive(srcPath, destPath, templateRoot, projectName);
68
+ }
69
+ } else {
70
+ const skip =
71
+ EXCLUDE_FILES.has(entry.name) ||
72
+ entry.name === '.env' ||
73
+ (entry.name.startsWith('.env') && !entry.name.endsWith('.example'));
74
+ if (!skip) fs.copyFileSync(srcPath, destPath);
75
+ }
76
+ }
77
+
78
+ // Copy .env.example to .env in the new project
79
+ const envExample = path.join(templateRoot, '.env.example');
80
+ if (fs.existsSync(envExample)) {
81
+ fs.copyFileSync(envExample, path.join(targetDir, '.env'));
82
+ }
83
+
84
+ console.log('Installing dependencies...');
85
+ const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
86
+
87
+ const install = spawnSync(npmCmd, ['install'], {
88
+ cwd: targetDir,
89
+ stdio: 'inherit',
90
+ });
91
+ if (install.status !== 0) {
92
+ console.error('npm install failed. You can run it manually inside the project.');
93
+ process.exit(install.status || 1);
94
+ }
95
+
96
+ console.log('');
97
+ console.log(`Done! Your app is in ./${projectName}`);
98
+ console.log('');
99
+ console.log('Next steps:');
100
+ console.log(` cd ${projectName}`);
101
+ console.log(' cp .env.example .env # then edit .env with your settings');
102
+ console.log(' npm run dev # start development server');
103
+ console.log('');
104
+ }
105
+
106
+ main();
@@ -0,0 +1,4 @@
1
+ services:
2
+ node-app:
3
+ container_name: node-app-dev
4
+ command: npm run dev