{"id":21445848,"url":"https://github.com/developer-sujon/task-todo","last_synced_at":"2025-03-17T01:23:31.523Z","repository":{"id":161617308,"uuid":"622666243","full_name":"developer-sujon/task-todo","owner":"developer-sujon","description":null,"archived":false,"fork":false,"pushed_at":"2023-09-03T13:25:34.000Z","size":6703,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-23T11:20:08.595Z","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":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/developer-sujon.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-04-02T19:17:27.000Z","updated_at":"2023-05-04T13:17:04.000Z","dependencies_parsed_at":"2024-01-23T12:10:13.727Z","dependency_job_id":null,"html_url":"https://github.com/developer-sujon/task-todo","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/developer-sujon%2Ftask-todo","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/developer-sujon%2Ftask-todo/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/developer-sujon%2Ftask-todo/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/developer-sujon%2Ftask-todo/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/developer-sujon","download_url":"https://codeload.github.com/developer-sujon/task-todo/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243955729,"owners_count":20374374,"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":"2024-11-23T02:39:24.008Z","updated_at":"2025-03-17T01:23:31.517Z","avatar_url":"https://github.com/developer-sujon.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Task\n\n## Quick Start\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## Table of Contents\n\n- [Task](#task)\n  - [Quick Start](#quick-start)\n  - [Table of Contents](#table-of-contents)\n  - [Features](#features)\n  - [Commands](#commands)\n  - [Environment Variables](#environment-variables)\n  - [Project Structure](#project-structure)\n  - [API Documentation](#api-documentation)\n    - [API Endpoints](#api-endpoints)\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    - [toJSON](#tojson)\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## 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=6100\n\n# URL of the Mongo DB\nMONGODB_URL=mongodb://127.0.0.1:27017/task-hellwet-soft\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#api path\nAPI_PATH=/api/v1\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#NODE_ENV\nNODE_ENV=development\n\n## Project Structure\n\n```\nsrc\\\n |--config\\         # Environment variables and configuration related things\n |--controllers\\    # Route controllers (controller layer)\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/logout` - logout\\\n`POST /v1/auth/refresh-tokens` - refresh auth tokens\\\n`POST /v1/auth/forgotPassword` - send reset password email\\\n`POST /v1/auth/verifyEmail` - verify email\n`POST /v1/auth/resetPassword` - reset password\\\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# anf3\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeveloper-sujon%2Ftask-todo","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdeveloper-sujon%2Ftask-todo","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeveloper-sujon%2Ftask-todo/lists"}