{"id":24979988,"url":"https://github.com/sajaltimilsina/natour---node-api","last_synced_at":"2026-04-13T03:03:22.718Z","repository":{"id":214445048,"uuid":"736036464","full_name":"SajalTimilsina/Natour---Node-API","owner":"SajalTimilsina","description":"Backend API for Tour company- includes User authentication, JWT token, login, signup, forget password, Access management, CURD on Tour and Reviews \u0026 many more features.","archived":false,"fork":false,"pushed_at":"2024-11-25T06:18:28.000Z","size":30345,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-02-04T04:31:13.895Z","etag":null,"topics":["aliasing","data-modeling","data-sanitization","event-loop","express","jwt-authentication","mongoose","nodejs","nodemailer","pagination","sorting","thread"],"latest_commit_sha":null,"homepage":"https://documenter.getpostman.com/view/30945305/2s9YkuYyCW","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/SajalTimilsina.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-12-26T19:58:18.000Z","updated_at":"2024-11-25T06:21:25.000Z","dependencies_parsed_at":"2025-02-04T04:39:45.780Z","dependency_job_id":null,"html_url":"https://github.com/SajalTimilsina/Natour---Node-API","commit_stats":null,"previous_names":["sajaltimilsina/natour---node-api"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SajalTimilsina%2FNatour---Node-API","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SajalTimilsina%2FNatour---Node-API/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SajalTimilsina%2FNatour---Node-API/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SajalTimilsina%2FNatour---Node-API/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/SajalTimilsina","download_url":"https://codeload.github.com/SajalTimilsina/Natour---Node-API/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246168086,"owners_count":20734389,"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":["aliasing","data-modeling","data-sanitization","event-loop","express","jwt-authentication","mongoose","nodejs","nodemailer","pagination","sorting","thread"],"created_at":"2025-02-04T04:29:02.873Z","updated_at":"2026-04-13T03:03:22.657Z","avatar_url":"https://github.com/SajalTimilsina.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# MERN Stack Application - API Server\n\nThis project is a **backend API** for a tour company, built using **Node.js**, **Express**, and **MongoDB**. It provides robust CRUD operations for tours, users, and reviews, along with advanced features like `JWT-based authentication`, `role-based authorization`, and `comprehensive error handling`. The application employs modern web development practices, including **modular architecture**, **reusable factory functions**, and **middleware**, ensuring maintainability, **scalability**, and **security**. Key security measures such as `data sanitization`, `rate limiting`, and setting `HTTP headers` are implemented to protect against common web vulnerabilities.\n\n - Publish API Document: (https://documenter.getpostman.com/view/30543767/2sAYBUECo7)\n - Hosted Live API: https://natour-api.vercel.app/\n \n\u003cimg width=\"942\" alt=\"Capture\" src=\"https://github.com/user-attachments/assets/b342ed80-3533-492e-b9fa-b6de89718f7d\"\u003e\n\u003cimg width=\"942\" alt=\"Capture2\" src=\"https://github.com/user-attachments/assets/236067b7-624d-4a5b-b2be-fc7c22ddfe5c\"\u003e\n\n## Core Features \u0026 Coding practices:\n- **Modular Architecture:** Organized into `models`, `controllers`, `routes`, and `utilities` for scalability and maintainability.  \n- **Factory Functions:** Reusable functions for `CRUD` operations to reduce duplication and ensure consistency.  \n- **Middleware:** Used for authentication, authorization, error handling, and data sanitization.  \n- **Utility Classes:** Tools like `APIFeatures` simplify complex query handling (e.g., `filtering` and `pagination`).  \n- **Security:** Includes `data sanitization`, `rate limiting`, and `secure HTTP headers` to prevent vulnerabilities.  \n- **Environment Configuration:** Uses environment variables for flexible and secure deployment across environments.\n\n## Achievements\n- **CRUD Operations:** Implemented robust CRUD operations for tours, users, and reviews.  \n- **Authentication and Authorization:** Developed JWT-based authentication and role-based access control.  \n- **Error Handling:** Centralized error handling using custom error classes and middleware.  \n- **Data Validation and Sanitization:** Ensured data integrity and security through validation and sanitization.  \n- **Pagination, Sorting, and Filtering:** Added advanced query features for listing resources efficiently.  \n- **Scalability:** Designed the application to be scalable using best practices and modular architecture.  \n\n## Leveraging Modern Web Development Practices\n\n### 1. Factory Functions\n\n- **Purpose:** Reduce code duplication and ensure consistency across the application.  \n- **Example:** The `handlerFactory.js` file contains reusable functions for CRUD operations.  \n\n```javascript\nexports.deleteOne = (Model) =\u003e\n  catchAsync(async (req, res, next) =\u003e {\n    const doc = await Model.findByIdAndDelete(req.params.id);\n    if (!doc) {\n      return next(new AppError(`Cannot find document with id of ${req.params.id}`, 404));\n    }\n    res.status(204).json({\n      status: 'success',\n      data: null,\n    });\n  });\n```\n\n### 2. Middleware\n\n- **Purpose:** Middleware functions handle tasks such as authentication, authorization, error handling, and data sanitization, promoting modularity and maintainability.  \n- **Examples:**\n\n#### Logging Middleware  \nLogs requests in development mode for better debugging and monitoring:  \n\n```javascript\nif (process.env.NODE_ENV === 'development') {\n  app.use(morgan('dev'));\n}\n```\n\n## Leveraging Modern Web Development Practices\n\n### Authentication\n\n- **Purpose:** Secure the application by ensuring only authorized users can access specific resources.  \n- **Example:** JWT-based authentication to verify and manage user access.  \n\n#### 3. Authentication Middleware:  \n\nThe middleware validates tokens, checks user existence, and attaches the user data to the request for further processing:  \n\n```javascript\nconst protect = catchAsync(async (req, res, next) =\u003e {\n  let token;\n  if (req.headers.authorization \u0026\u0026 req.headers.authorization.startsWith('Bearer')) {\n    token = req.headers.authorization.split(' ')[1];\n  }\n  if (!token) {\n    return next(new AppError('You are not logged in! Please log in to get access.', 401));\n  }\n  // Validate token and attach user info to the request\n  const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);\n  const currentUser = await User.findById(decoded.id);\n  if (!currentUser) {\n    return next(new AppError('The user belonging to this token does not exist.', 401));\n  }\n  req.user = currentUser;\n  next();\n});\n```\n### 4. Utility Classes\n\n- **Purpose:** The `APIFeatures` class simplifies complex query operations for MongoDB by breaking them into reusable, modular functions. It handles filtering, sorting, field limiting, and pagination of query results.\n---\n### Explanation of `APIFeatures` Functions\n\n#### 1. **filter()**  \n- **Functionality:**  \n  Filters query parameters by removing special fields (e.g., `page`, `limit`, `sort`, `fields`) and processes conditions like greater than (`gte`), less than (`lt`), etc.  \n- **How It Works:**  \n  - Copies the query object and removes fields that are not needed for filtering.  \n  - Converts MongoDB-specific operators into a query-friendly format.  \n  - Applies the processed filters to the database query.  \n\n```javascript\nfilter() {\n  const queryObj = { ...this.queryString };\n  const excludedFields = ['page', 'limit', 'sort', 'fields'];\n  excludedFields.forEach(el =\u003e delete queryObj[el]);\n\n  let queryStr = JSON.stringify(queryObj);\n  queryStr = queryStr.replace(/\\b(gte|gt|lte|lt)\\b/g, match =\u003e `$${match}`);\n\n  this.query = this.query.find(JSON.parse(queryStr));\n  return this;\n// ... to be continued in the repo\n}\n```\n\n\n## Conclusion\nBy leveraging modern web development practices such as factory functions, middleware, and utility classes, this project achieves a high level of maintainability, scalability, and readability. The modular architecture ensures that each component is responsible for a specific task, making the codebase easier to manage and extend. The use of security measures and environment configuration further enhances the robustness and flexibility of the application.\n\n## Implementation: Follow these Steps:\n\nThe available scripts for the server include:\n\n```plaintext\nnpm start         # Starts the server in development mode\nnpm run start:prod # Sets the server in production mode\nnpm run debug     # Runs the server in debug mode using NDB\n```\n\n## Dependencies\n\nThe server uses various dependencies:\n\n```plaintext\nexpress:           Web framework for Node.js to handle routes and requests.\nmongoose:          ODM library for MongoDB, facilitating interaction with the database.\njsonwebtoken:      Helps in generating and verifying JSON Web Tokens (JWT) for user authentication.\nbcryptjs:          A library for hashing passwords.\nnodemailer:        Used for sending emails in the application.\ndotenv:            Loads environment variables from a .env file into process.env.\n```\n\n## Middleware\n\nThe server employs several middleware functions:\n\n - express-rate-limit: Limits repeated requests from the same IP.\n - helmet: Sets various HTTP headers to enhance security.\n - express-mongo-sanitize: Sanitizes data to prevent NoSQL injection attacks.\n - xss-clean: Prevents Cross-Site Scripting (XSS) attacks.\n - hpp: Helps in preventing HTTP Parameter Pollution attacks.\n\n## Environment Variables\n```markdown\nTo set up the server, ensure the following environment variables are configured:\n\n\nNODE_ENV: Set to development or production.\nPORT: Port number for the server.\nUSER: Your username for the database.\nDATABASE: MongoDB connection string.\nDATABASE_PASSWORD: Password for the database.\nJWT_SECRET: Secret key for JWT token generation.\nJWT_EXPIRES_IN: Expiry time for JWT tokens.\nJWT_COOKIE_EXPIRES_IN: Expiry time for JWT cookies.\nEMAIL_USERNAME: Username for sending emails.\nEMAIL_PASSWORD: Password for the email account.\nEMAIL_HOSTNAME: SMTP hostname for sending emails.\nEMAIL_PORT: Port number for the email service.\n```\n\n## Usage\n\n1. Clone this repository: `git clone \u003crepository-url\u003e`\n2. Install dependencies: `npm install`\n3. Set up environment variables as specified in `.env` file.\n4. Start the server:\n   - Development Mode: `npm start`\n   - Production Mode: `npm run start:prod`\n   - Debug Mode: `npm run debug`\n\n## Contribution\n\nContributions, bug reports, and feature suggestions are welcome. To contribute:\n1. Fork the repository.\n2. Create a new branch: `git checkout -b feature-name`\n3. Make changes and commit them: `git commit -m 'Add feature'`\n4. Push to the branch: `git push origin feature-name`\n5. Open a pull request.\n\n## License\n\nThis project is licensed under the ISC License. Feel free to use, modify, or distribute the code as per the terms of this license.\n```\n\nPlease replace placeholders like `\u003cPASSWORD\u003e` and `your_username_here` with actual values in your `.env` file and project-specific information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsajaltimilsina%2Fnatour---node-api","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsajaltimilsina%2Fnatour---node-api","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsajaltimilsina%2Fnatour---node-api/lists"}