{"id":26938914,"url":"https://github.com/doank15/expressbasic","last_synced_at":"2025-04-02T14:15:20.532Z","repository":{"id":188657690,"uuid":"501716129","full_name":"doank15/Expressbasic","owner":"doank15","description":null,"archived":false,"fork":false,"pushed_at":"2022-06-09T15:47:52.000Z","size":140,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2023-08-16T10:04:36.334Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/doank15.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2022-06-09T15:47:50.000Z","updated_at":"2023-08-16T10:04:38.030Z","dependencies_parsed_at":"2023-08-16T10:15:00.366Z","dependency_job_id":null,"html_url":"https://github.com/doank15/Expressbasic","commit_stats":null,"previous_names":["doank15/expressbasic"],"tags_count":null,"template":null,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/doank15%2FExpressbasic","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/doank15%2FExpressbasic/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/doank15%2FExpressbasic/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/doank15%2FExpressbasic/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/doank15","download_url":"https://codeload.github.com/doank15/Expressbasic/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246828505,"owners_count":20840474,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-04-02T14:15:19.661Z","updated_at":"2025-04-02T14:15:20.522Z","avatar_url":"https://github.com/doank15.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# RESTful API Node Server Boilerplate\n\n[![Build Status](https://travis-ci.org/hagopj13/node-express-boilerplate.svg?branch=master)](https://travis-ci.org/hagopj13/node-express-boilerplate)\n[![Coverage Status](https://coveralls.io/repos/github/hagopj13/node-express-boilerplate/badge.svg?branch=master)](https://coveralls.io/github/hagopj13/node-express-boilerplate?branch=master)\n[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)\n\nA boilerplate/starter project for quickly building RESTful APIs using Node.js, Express, and Mongoose.\n\nBy 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.\n\n## Quick Start\n\nTo create a project, simply run:\n\n```bash\nnpx create-nodejs-express-app \u003cproject-name\u003e\n```\n\nOr\n\n```bash\nnpm init nodejs-express-app \u003cproject-name\u003e\n```\n\n## Manual Installation\n\nIf you would still prefer to do the installation manually, follow these steps:\n\nClone the repo:\n\n```bash\ngit clone --depth 1 https://github.com/hagopj13/node-express-boilerplate.git\ncd node-express-boilerplate\nnpx rimraf ./.git\n```\n\nInstall the dependencies:\n\n```bash\nyarn install\n```\n\nSet the environment variables:\n\n```bash\ncp .env.example .env\n\n# open .env and modify the environment variables (if needed)\n```\n\n## Table of Contents\n\n- [Features](#features)\n- [Commands](#commands)\n- [Environment Variables](#environment-variables)\n- [Project Structure](#project-structure)\n- [API Documentation](#api-documentation)\n- [Error Handling](#error-handling)\n- [Validation](#validation)\n- [Authentication](#authentication)\n- [Authorization](#authorization)\n- [Logging](#logging)\n- [Custom Mongoose Plugins](#custom-mongoose-plugins)\n- [Linting](#linting)\n- [Contributing](#contributing)\n\n## Features\n\n- **NoSQL database**: [MongoDB](https://www.mongodb.com) object data modeling using [Mongoose](https://mongoosejs.com)\n- **Authentication and authorization**: using [passport](http://www.passportjs.org)\n- **Validation**: request data validation using [Joi](https://github.com/hapijs/joi)\n- **Logging**: using [winston](https://github.com/winstonjs/winston) and [morgan](https://github.com/expressjs/morgan)\n- **Testing**: unit and integration tests using [Jest](https://jestjs.io)\n- **Error handling**: centralized error handling mechanism\n- **API documentation**: with [swagger-jsdoc](https://github.com/Surnet/swagger-jsdoc) and [swagger-ui-express](https://github.com/scottie1984/swagger-ui-express)\n- **Process management**: advanced production process management using [PM2](https://pm2.keymetrics.io)\n- **Dependency management**: with [Yarn](https://yarnpkg.com)\n- **Environment variables**: using [dotenv](https://github.com/motdotla/dotenv) and [cross-env](https://github.com/kentcdodds/cross-env#readme)\n- **Security**: set security HTTP headers using [helmet](https://helmetjs.github.io)\n- **Santizing**: sanitize request data against xss and query injection\n- **CORS**: Cross-Origin Resource-Sharing enabled using [cors](https://github.com/expressjs/cors)\n- **Compression**: gzip compression with [compression](https://github.com/expressjs/compression)\n- **CI**: continuous integration with [Travis CI](https://travis-ci.org)\n- **Docker support**\n- **Code coverage**: using [coveralls](https://coveralls.io)\n- **Code quality**: with [Codacy](https://www.codacy.com)\n- **Git hooks**: with [husky](https://github.com/typicode/husky) and [lint-staged](https://github.com/okonet/lint-staged)\n- **Linting**: with [ESLint](https://eslint.org) and [Prettier](https://prettier.io)\n- **Editor config**: consistent editor configuration using [EditorConfig](https://editorconfig.org)\n\n## Commands\n\nRunning locally:\n\n```bash\nyarn dev\n```\n\nRunning in production:\n\n```bash\nyarn start\n```\n\nTesting:\n\n```bash\n# run all tests\nyarn test\n\n# run all tests in watch mode\nyarn test:watch\n\n# run test coverage\nyarn coverage\n```\n\nDocker:\n\n```bash\n# run docker container in development mode\nyarn docker:dev\n\n# run docker container in production mode\nyarn docker:prod\n\n# run all tests in a docker container\nyarn docker:test\n```\n\nLinting:\n\n```bash\n# run ESLint\nyarn lint\n\n# fix ESLint errors\nyarn lint:fix\n\n# run prettier\nyarn prettier\n\n# fix prettier errors\nyarn prettier:fix\n```\n\n## Environment Variables\n\nThe environment variables can be found and modified in the `.env` file. They come with these default values:\n\n```bash\n# Port number\nPORT=3000\n\n# URL of the Mongo DB\nMONGODB_URL=mongodb://127.0.0.1:27017/node-boilerplate\n\n# JWT\n# JWT secret key\nJWT_SECRET=thisisasamplesecret\n# Number of minutes after which an access token expires\nJWT_ACCESS_EXPIRATION_MINUTES=30\n# Number of days after which a refresh token expires\nJWT_REFRESH_EXPIRATION_DAYS=30\n\n# SMTP configuration options for the email service\n# For testing, you can use a fake SMTP service like Ethereal: https://ethereal.email/create\nSMTP_HOST=email-server\nSMTP_PORT=587\nSMTP_USERNAME=email-server-username\nSMTP_PASSWORD=email-server-password\nEMAIL_FROM=support@yourapp.com\n```\n\n## Project Structure\n\n```\nsrc\\\n |--config\\         # Environment variables and configuration related things\n |--controllers\\    # Route controllers (controller layer)\n |--docs\\           # Swagger files\n |--middlewares\\    # Custom express middlewares\n |--models\\         # Mongoose models (data layer)\n |--routes\\         # Routes\n |--services\\       # Business logic (service layer)\n |--utils\\          # Utility classes and functions\n |--validations\\    # Request data validation schemas\n |--app.js          # Express app\n |--index.js        # App entry point\n```\n\n## API Documentation\n\nTo 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.\n\n### API Endpoints\n\nList of available routes:\n\n**Auth routes**:\\\n`POST /v1/auth/register` - register\\\n`POST /v1/auth/login` - login\\\n`POST /v1/auth/refresh-tokens` - refresh auth tokens\\\n`POST /v1/auth/forgot-password` - send reset password email\\\n`POST /v1/auth/reset-password` - reset password\\\n`POST /v1/auth/send-verification-email` - send verification email\\\n`POST /v1/auth/verify-email` - verify email\n\n**User routes**:\\\n`POST /v1/users` - create a user\\\n`GET /v1/users` - get all users\\\n`GET /v1/users/:userId` - get user\\\n`PATCH /v1/users/:userId` - update user\\\n`DELETE /v1/users/:userId` - delete user\n\n## Error Handling\n\nThe app has a centralized error handling mechanism.\n\nControllers 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.\n\n```javascript\nconst catchAsync = require('../utils/catchAsync');\n\nconst controller = catchAsync(async (req, res) =\u003e {\n  // this error will be forwarded to the error handling middleware\n  throw new Error('Something wrong happened');\n});\n```\n\nThe error handling middleware sends an error response, which has the following format:\n\n```json\n{\n  \"code\": 404,\n  \"message\": \"Not found\"\n}\n```\n\nWhen running in development mode, the error response also contains the error stack.\n\nThe 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).\n\nFor 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:\n\n```javascript\nconst httpStatus = require('http-status');\nconst ApiError = require('../utils/ApiError');\nconst User = require('../models/User');\n\nconst getUser = async (userId) =\u003e {\n  const user = await User.findById(userId);\n  if (!user) {\n    throw new ApiError(httpStatus.NOT_FOUND, 'User not found');\n  }\n};\n```\n\n## Validation\n\nRequest 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.\n\nThe validation schemas are defined in the `src/validations` directory and are used in the routes by providing them as parameters to the `validate` middleware.\n\n```javascript\nconst express = require('express');\nconst validate = require('../../middlewares/validate');\nconst userValidation = require('../../validations/user.validation');\nconst userController = require('../../controllers/user.controller');\n\nconst router = express.Router();\n\nrouter.post('/users', validate(userValidation.createUser), userController.createUser);\n```\n\n## Authentication\n\nTo require authentication for certain routes, you can use the `auth` middleware.\n\n```javascript\nconst express = require('express');\nconst auth = require('../../middlewares/auth');\nconst userController = require('../../controllers/user.controller');\n\nconst router = express.Router();\n\nrouter.post('/users', auth(), userController.createUser);\n```\n\nThese 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.\n\n**Generating Access Tokens**:\n\nAn 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).\n\nAn 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.\n\n**Refreshing Access Tokens**:\n\nAfter 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.\n\nA 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.\n\n## Authorization\n\nThe `auth` middleware can also be used to require certain rights/permissions to access a route.\n\n```javascript\nconst express = require('express');\nconst auth = require('../../middlewares/auth');\nconst userController = require('../../controllers/user.controller');\n\nconst router = express.Router();\n\nrouter.post('/users', auth('manageUsers'), userController.createUser);\n```\n\nIn the example above, an authenticated user can access this route only if that user has the `manageUsers` permission.\n\nThe permissions are role-based. You can view the permissions/rights of each role in the `src/config/roles.js` file.\n\nIf the user making the request does not have the required permissions to access this route, a Forbidden (403) error is thrown.\n\n## Logging\n\nImport the logger from `src/config/logger.js`. It is using the [Winston](https://github.com/winstonjs/winston) logging library.\n\nLogging should be done according to the following severity levels (ascending order from most important to least important):\n\n```javascript\nconst logger = require('\u003cpath to src\u003e/config/logger');\n\nlogger.error('message'); // level 0\nlogger.warn('message'); // level 1\nlogger.info('message'); // level 2\nlogger.http('message'); // level 3\nlogger.verbose('message'); // level 4\nlogger.debug('message'); // level 5\n```\n\nIn development mode, log messages of all severity levels will be printed to the console.\n\nIn production mode, only `info`, `warn`, and `error` logs will be printed to the console.\\\nIt is up to the server (or process manager) to actually read them from the console and store them in log files.\\\nThis app uses pm2 in production mode, which is already configured to store the logs in log files.\n\nNote: API request information (request url, response code, timestamp, etc.) are also automatically logged (using [morgan](https://github.com/expressjs/morgan)).\n\n## Custom Mongoose Plugins\n\nThe 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`.\n\n```javascript\nconst mongoose = require('mongoose');\nconst { toJSON, paginate } = require('./plugins');\n\nconst userSchema = mongoose.Schema(\n  {\n    /* schema definition here */\n  },\n  { timestamps: true }\n);\n\nuserSchema.plugin(toJSON);\nuserSchema.plugin(paginate);\n\nconst User = mongoose.model('User', userSchema);\n```\n\n### toJSON\n\nThe toJSON plugin applies the following changes in the toJSON transform call:\n\n- removes \\_\\_v, createdAt, updatedAt, and any schema path that has private: true\n- replaces \\_id with id\n\n### paginate\n\nThe paginate plugin adds the `paginate` static method to the mongoose schema.\n\nAdding this plugin to the `User` model schema will allow you to do the following:\n\n```javascript\nconst queryUsers = async (filter, options) =\u003e {\n  const users = await User.paginate(filter, options);\n  return users;\n};\n```\n\nThe `filter` param is a regular mongo filter.\n\nThe `options` param can have the following (optional) fields:\n\n```javascript\nconst options = {\n  sortBy: 'name:desc', // sort order\n  limit: 5, // maximum results per page\n  page: 2, // page number\n};\n```\n\nThe plugin also supports sorting by multiple criteria (separated by a comma): `sortBy: name:desc,role:asc`\n\nThe `paginate` method returns a Promise, which fulfills with an object having the following properties:\n\n```json\n{\n  \"results\": [],\n  \"page\": 2,\n  \"limit\": 5,\n  \"totalPages\": 10,\n  \"totalResults\": 48\n}\n```\n\n## Linting\n\nLinting is done using [ESLint](https://eslint.org/) and [Prettier](https://prettier.io).\n\nIn 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.\n\nTo modify the ESLint configuration, update the `.eslintrc.json` file. To modify the Prettier configuration, update the `.prettierrc.json` file.\n\nTo prevent a certain file or directory from being linted, add it to `.eslintignore` and `.prettierignore`.\n\nTo maintain a consistent coding style across different IDEs, the project contains `.editorconfig`\n\n## Contributing\n\nContributions are more than welcome! Please check out the [contributing guide](CONTRIBUTING.md).\n\n## Inspirations\n\n- [danielfsousa/express-rest-es2017-boilerplate](https://github.com/danielfsousa/express-rest-es2017-boilerplate)\n- [madhums/node-express-mongoose](https://github.com/madhums/node-express-mongoose)\n- [kunalkapadia/express-mongoose-es6-rest-api](https://github.com/kunalkapadia/express-mongoose-es6-rest-api)\n\n## License\n\n[MIT](LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdoank15%2Fexpressbasic","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdoank15%2Fexpressbasic","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdoank15%2Fexpressbasic/lists"}