GithubHelp home page GithubHelp logo

hiteshchoudhary / apihub Goto Github PK

View Code? Open in Web Editor NEW
2.8K 39.0 639.0 2.75 MB

Your own API Hub to learn and master API interaction. Ideal for frontend, mobile dev and backend developers.

Home Page: https://freeapi.app

License: Other

Dockerfile 0.14% JavaScript 99.61% HTML 0.20% Shell 0.05%
api backend backend-api frontend mobile-development

apihub's Introduction

FreeAPI.app

Problem

We are trying to build a single source API hub that can be used to learn api handling in any programming language. Users can build their front end portfolio in web and mobile apps using this api hub.

What is FreeAPI.app

The FreeAPI project is an innovative and community-driven initiative aimed at providing developers with free and accessible APIs for their projects.

The project focuses on delivering a wide range of APIs that cater to various domains and functionalities, enabling developers to seamlessly integrate these APIs into their applications.

Key highlights of the FreeAPI project include:

  1. Accessibility: The FreeAPI project is committed to eliminating barriers by providing free access to its collection of APIs. Developers can leverage these APIs without any cost limitations, allowing them to experiment, learn, and build innovative applications.

  2. Diverse API Collection: The project offers a diverse and comprehensive collection of APIs that span across different industries, domains, and functionalities. Whether you require social media integrations, payment gateways, machine learning algorithms, or IoT device connectivity, the FreeAPI project has you covered.

  3. Simplified Integration: The FreeAPI project understands the challenges developers face when integrating APIs into their applications. To address this, the project provides clear documentation, code samples, and SDKs, simplifying the integration process and reducing development time and effort.

  4. Community-Driven Development: The project fosters a vibrant and collaborative community of developers. Contributors are encouraged to share their knowledge, engage in discussions, and collaborate on API-related projects. This collective effort ensures the continuous improvement and reliability of the APIs offered by the FreeAPI project.

  5. Learning and Skill Development: The FreeAPI project aims to empower developers by providing a platform for learning and skill development. Through access to various APIs and educational resources, developers can enhance their understanding of API integration, expand their knowledge, and showcase their expertise through building complete projects.

Overall, the FreeAPI project is a valuable resource for developers seeking accessible and diverse APIs.

By fostering a supportive community, the project empowers developers to learn, create, and innovate, ultimately contributing to the growth and advancement of the API integration landscape.

Features:

Introducing our groundbreaking open source API hub project, a dynamic platform designed to revolutionize the way developers interact with APIs.

With an emphasis on openness, accessibility, and learning, our API hub empowers developers of all levels to explore, experiment, and grow their skills in API integration.

Highlights:

  1. Open Source: Our API hub is built on the principles of open source, ensuring transparency, collaboration, and community-driven development. This means that the source code is freely available, allowing developers to customize, extend, and contribute to the project.

  2. Free to Use: We firmly believe in removing barriers to entry, which is why our API hub is completely free to use. Whether you're a seasoned developer or just starting your coding journey, you can leverage our platform without any cost limitations.

  3. Local or Deployment: Flexibility is at the core of our API hub. You have the option to use it locally, running on your own machine, or deploy it to a server, making it accessible to others. This versatility ensures that you can adapt the platform to your specific development environment.

  4. Learning Resource: Our API hub is designed as a comprehensive learning resource, offering a wealth of educational materials, tutorials, and documentation. Whether you're a beginner or seeking to expand your API knowledge, our platform provides the resources you need to learn and improve.

  5. Custom Endpoints for Beginners: For developers at the beginner level, our API hub offers custom endpoints that provide a hands-on experience in handling API responses. These beginner-friendly APIs allow you to practice and familiarize yourself with the basics of working with APIs.

  6. Advanced APIs for Portfolio Building: In addition to beginner-level endpoints, our API hub also provides advanced APIs to challenge and stretch your skills. These APIs enable you to tackle more complex integration scenarios, helping you build a robust portfolio of projects to showcase your expertise.

By combining open source principles, accessibility, and a focus on learning, our API hub project paves the way for developers to thrive in the world of API integration. Join our vibrant community and embark on an exciting journey of discovery, growth, and innovation.

⚠️ Important Note: Avoiding Data Loss and Self-Hosting

Background:

Our open-source project is currently hosted on a remote server, where we are forced to reset the entire server, including the file system and MongoDB database, every 2 hours to avoid incurring additional costs.

This process results in the deletion of all image/static files and a reset of the entire database on the server.

What does this mean for you?

Data Loss: Any changes made during the 2-hour interval (on the remote server), including uploaded images and user data, will be lost and unrecoverable.

Service Interruption: The server reset might disrupt your development and testing processes for a certain duration while the server is rebooting (for 1-2 minutes).

Recommended Solutions:

Local API Usage: For development and testing purposes, we strongly recommend using the API locally on your machine by cloning the project.

This ensures that your work is not affected by the server resets and allows you to maintain a stable development environment on your local machine.

Self-Hosting on Railway (recommended for personal projects): To self-host the FreeAPI.app application, you can take advantage of a pre-built template that is readily available. Click here for detailed docs

🏁 Installation

📦 Using Docker (recommended)

To run the FreeAPI project, follow these steps:

  1. Install Docker on your machine.
  2. Clone the project repository.
  3. Navigate to the project directory.
  4. Create .env file in the root folder and copy paste the content of .env.sample, and add necessary credentials.
  5. Run the Docker Compose command:
docker-compose up --build --attach backend

# --build: Rebuild the image and run the containers
# --attach: only show logs of Node app container and not mongodb
  1. Access the project APIs at the specified endpoints.

💻 Running locally

To run the FreeAPI project locally, follow these steps:

  1. Install Yarn, NodeJs, MongoDB and MongoDB Compass (optional) on your machine.
  2. Clone the project repository.
  3. Navigate to the project directory.
  4. Create .env file in the root folder and copy paste the content of .env.sample, and add necessary credentials.
  5. Install the packages:
yarn install
  1. Run the project:
yarn start
  1. Access the project APIs at the specified endpoints.

🚄 Using Railway (One-click Deploy)

To self-host the FreeAPI.app application, you can take advantage of a pre-built template that is readily available.

Deploy FreeAPI.app

  1. Click the button above to visit railway.app.

  2. Click on the Deploy Now button.

  3. (Optional) Sign in with GitHub to deploy.

  4. Fill in the Repository details:

    • Specify the repo name (e.g., freeapi-app).
    • Checkmark for Public/Private repository.
  5. For Environment variables, we have provided some default values in the ENV to reduce the burden, but some parameters are mandatory:

    • PORT: Do not change the value, let it be set to 8080 to view the swagger docs after deployment.
    • MONGODB_URI: Provide the MongoDB Atlas database URL. An example is prefilled for you, edit/update it to continue.
    • NODE_ENV: Default set to 'development' to view the logs. You may choose to change it to 'production' (make sure to add exact same word) to hide them.
    • EXPRESS_SESSION_SECRET: It is advised to change the default value to your own secret value.
    • ACCESS_TOKEN_SECRET: It is advised to change the default value to your own secret value.
    • ACCESS_TOKEN_EXPIRY: Set to 1 day as default.
    • REFRESH_TOKEN_SECRET: It is advised to change the default value to your own secret value.
    • REFRESH_TOKEN_EXPIRY: Set to 10 days as default.
  6. Once you fill in the required environment parameters, if you choose to add others such as PayPal, Google, and Razorpay, please proceed to mention your credentials in the form.

  7. Click on the Deploy button to trigger the first build.

    • Monitor the server logs; if you come across any deployment problems, feel free to raise an issue for our team to look into.

Note: Once the application is deployed, please wait for 3-5 minutes for the swagger docs to be available.

🧪 Testing

To ensure reliability & stability for our end users, we utilize Playwright, a powerful testing framework to automate testing across all endpoints.

💻 Run the Test Server

Make sure to add MONGO_MEMORY_SERVER_PORT=10000 (mongodb port for e2e testing) in your .env file.

yarn start:test-server

🧪 Run Tests

yarn test:playwright

This will generate a Playwright report. To view this report run the following command

yarn playwright show-report

Make sure all the test cases are passed whenever you make any changes.

How to contribute - Guidelines

⚡️ Contribute in core FreeAPI codebase:

We welcome your interest in contributing to our open source project!

To contribute to FreeAPI, please follow these steps:

  1. Fork the repository.
  2. Create a new branch for your feature or bug fix: git checkout -b feat/your-feature-name or git checkout -b fix/your-bug-fix-name and make your changes.
  3. Run all the tests 🧪 before committing the changes and make sure all tests are passed.
  4. After all tests are passed, commit your changes with a descriptive messages: git commit -am 'add your commit message'
  5. For more details on the commit format and other guidelines, please refer to the Contributor Guidelines.
  6. Push your changes to your forked repository: git push origin feat/your-feature-name.
  7. Submit a pull request to the main repository, explaining the changes you've made and providing any necessary details.

Here's a guide on how you can effectively contribute to our API hub:

  1. Pull Requests for Readme Updates: Please refrain from sending pull requests solely for updating the project's readme file. While we appreciate the importance of clear and concise documentation, we prefer to focus on substantial code contributions and feature enhancements.

  2. Grammar Updates: Our team values effective communication, but we're not grammar sticklers. You don't need to send pull requests solely for grammar fixes or minor language improvements. Instead, concentrate on the core functionalities and features of the project.

  3. Avoid Updating Existing Public APIs: To maintain stability and consistency, we discourage direct updates to existing public APIs within the API hub. These APIs have been thoroughly tested and approved. However, if you encounter any bugs or issues, we encourage you to open an issue on our project's issue tracker to notify us.

  4. Build New Project APIs: We encourage you to explore your creativity and contribute by building complete project APIs. These APIs should provide comprehensive solutions that can assist developers in constructing complex projects to showcase their skills and abilities. Your contributions in this area will greatly benefit the community.

  5. Draft a Proposal and Discuss on Discord: Before diving into your project, we recommend drafting a proposal. This can include a mind map or outline of the API you intend to build and its potential benefits. Join our Discord community, where you can share your proposal, discuss ideas, and gather feedback from fellow contributors. Engaging in these discussions will enhance your backend portfolio and help shape the future direction of the project.

We appreciate your enthusiasm and look forward to your valuable contributions to our open source API hub project.

Together, we can foster a collaborative environment and make a significant impact in the API integration landscape.

Click here for detailed contribution guide.

🚀 Contribute by creating frontend application:

Thank you for your interest in contributing to the FreeAPI project by creating frontend applications consuming FreeAPIs! Your efforts play a crucial role in enhancing the user experience and expanding the reach of our APIs. Please follow this guide to ensure a smooth and collaborative contribution process.

Click here for detailed contribution guide for Frontend Developers 🚀!

🧪 Contribute in testing suite

Thank you for your interest in contributing to the FreeAPI project to increase code coverage of our API service that helps us to ship robust endpoints that are battlefield tested. Please follow this guide to ensure a smooth and collaborative contribution process.

Click here for detailed contribution guide for increasing code coverage.

📜 Swagger Docs

Swagger Docs: https://api.freeapi.app

apihub's People

Contributors

arnb-smnta avatar balaji-sivasakthi avatar dependabot[bot] avatar eltociear avatar hiteshchoudhary avatar jwala-anirudh avatar rudra-patel-code avatar sa-rang avatar sangamesh1439 avatar sarthak-ons avatar sarthak-troopr avatar shrey-dadhaniya avatar tarun-kavipurapu avatar vvek1402 avatar wajeshubham avatar wajeshubham-schbang avatar wajeshubhamsq avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

apihub's Issues

BUG : Can't access localhost:8080 on docker, <ip-address>:8080 produce cors error on fetching

Describe the bug

I tried to use localy by clone and npm install it works fine and i can access it via http://localhost:8080. But if i use docker, it wont work on http://localhost:8080 instead it will use the ip of that docker and yes i can access it via http://192.168.1.16:8080. The problem is that when i tried to make api request or like populate the data for todo or ecommerce it will tell me cors error, network failure, http and https stuff. but i think it all realated to the thing is http://localhost:8080 inaccessable

To Reproduce

just try to install it using the instruction as in this repo suggest, followw exact same steps:

  • Install Docker (I have docker on an linux not windows, not macos)
  • Clone the project repository.
  • Navigate to the project directory.
  • Create .env file in the root folder and copy paste the content of .env.sample, and add necessary credentials.
  • Run the Docker Compose

Docker up and running, can't access locahost:8080 but can access 192.168.1.16:8080

Expected behavior

A clear and concise description of what you expected to happen.
A way to make it accessable via localhost:8080 or if not 192.168.1.16:808 shouldn't produce the cors err when fetching data

Screenshots

If applicable, add screenshots to help explain your problem.

image

Screenshot 2023-08-31 at 15 37 29

Desktop (please complete the following information):

  • OS: Ubuntu linux 22.10
  • Client : Google Chrome
  • Version [e.g. 22]

Additional context

Add any other context about the problem here.

To fix mongoose prototype pollution vulnerability

Description

To upgrade mongoose to version 7.3.3 or later

Package version that currently in use is vulnerable to Prototype Pollution. Mongoose has fixed this in their release of 7.3.3

The mongoose.Schema() function is subject to prototype pollution due to the recursively calling of Schema.prototype.add() function to add new items into the schema object. This vulnerability allows modification of the Object prototype.

Severity

Low

Effected Files

  • src/models/apps/auth/user.models.js:162
  • src/models/apps/ecommerce/address.models.js:40
  • src/models/apps/ecommerce/cart.models.js:39
  • src/models/apps/ecommerce/category.models.js:21
  • src/models/apps/ecommerce/coupon.models.js:54
  • src/models/apps/ecommerce/order.models.js:78
  • src/models/apps/ecommerce/product.models.js:55
  • src/models/apps/ecommerce/profile.models.js:30
  • src/models/apps/social-media/bookmark.models.js:22
  • src/models/apps/social-media/comment.models.js:26
  • src/models/apps/social-media/follow.models.js:23
  • src/models/apps/social-media/like.models.js:26
  • src/models/apps/social-media/post.models.js:35
  • src/models/apps/social-media/profile.models.js:52
  • src/models/apps/todo/todo.models.js:22

Source

Prototype Pollution

Reproduction steps

Not applicable

Screenshots

Not applicable

Mongo db connection error in chat app

MongoDB connection error: MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://www.mongodb.com/docs/atlas/security-whitelist/
at _handleConnectionErrors (F:\apihub-main\apihub-main\node_modules\mongoose\lib\connection.js:788:11)
at NativeConnection.openUri (F:\apihub-main\apihub-main\node_modules\mongoose\lib\connection.js:763:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async connectDB (file:///F:/apihub-main/apihub-main/src/db/index.js:9:32) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(3) {
'ac-nodlse8-shard-00-00.iaka6gp.mongodb.net:27017' => [ServerDescription],
'ac-nodlse8-shard-00-02.iaka6gp.mongodb.net:27017' => [ServerDescription],
'ac-nodlse8-shard-00-01.iaka6gp.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'atlas-ppkt0r-shard-0',
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined
}
[nodemon] app crashed - waiting for file changes before starting...
I am getting this error again and again despite checking my ip address and cluster in network access section. I got this several times what to do??? I have tried every possible way to solve this but no results??

[enhancement]: Test suite with code coverage

Background

FreeApi.app as of today doesn't come with any test cases writtern for the application. I want to keep this as a open issue until we reach the goal of 50% coverage in phase 1.

Phase 2 would be to reach min code coverage of 80% for every subsequent release.

Plan

  • To utilise Jest for unit testing as it provides code coverage as well
  • To utilise Playwright for end-to-end testing
    • Need to use a third-party tool for reporting
    • No option of code coverage available that is built-in
  • Setup necessary packages & configuration to generate coverage report
  • To segregate various modules of FreeApi.app into buckets such as
    • Simple
    • Moderate
    • Complex
  • Test cases writing format must be at levels to ensure the quality of code
    • Unit
    • Integration
    • End-to-End

Outcome

  1. Improved code quality
  2. Avoid unnecessary bugs
  3. Confidence to refactor the code
  4. Easy review of PRs

Additional information

We will not be closing this issue until the stated Phases are achieved. Until then all are welcomed to contribute

BUG

Describe the bug

The bug is in the middlewares/verifyJWT in auth.middleware.js file

req.cookies?.accessToken || req.headers("Authorization")?.split(" ")[1];

Code breakdown whenever headers are not present, and ends up with Internal Server Error with a status code of 500.

To Reproduce

Steps to reproduce the behavior:

  1. In Postman, Select Authorization Type to No Auth.
  2. Then try to access a protected Route
  3. Then this error in screenshot below should appear.

Expected behavior

Whenever a "Authorization" header is not present, Server should send Unauthorized request.

Solution

Just change the way of accessing the headers.

req.cookies?.accessToken || req.headers["Authorization"]?.split(" ")[1];

Screenshots

image

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Client [e.g. postman, thunder client, chrome, safari]
  • Version [e.g. 22]

Additional context

Add any other context about the problem here.

chore: Improve Commit Rule and Husky Integration

I would like to propose an enhancement to the integration between Husky and commit rules. Currently, the combination of Husky and commit rules (e.g., Commitlint) provides an effective way to enforce commit message conventions, which is great for maintaining consistency and readability in Git repositories. However, I believe there is room for improvement to enhance the user experience and flexibility in configuring commit rules.

I want to work on this issue.

SUGGESION : Improvements in user's api response time by handling the data syncing/ initial set up part independently via mongodb change streams.

Hii, I would like to point out some improvements on how we are syncing the data between the different modules on user creation/update.

Reference:

Screenshot (8)

Problem:
The way we are doing it now it works fine, but it is affecting the user's api response time, as the user have to wait for all the queries to be executed in the post save hook. Besides by using the post save hook we're limiting the scope of using serveral methods such as update , findoneandupdate. see below image.

image

Suggestion :

I think we can achieve the simillar result by using Mongodb Change Streams. Basically when a change in user collection occurs we can listen for it and do the same data syncing part independently. Thus improving the response time of user's api. And I also believe it will be a better example to the people who will study from this codebase.

Setup Problem

As change streams needs a replica sets or sharded clusters to work. To setup the server locally the contributors will need to have the same. Which can be tough to set up. To handle this we can choose to use the current solution or mongodb change streams based on the Node Env.

Note:
If this suggestion seems reasonable let me know I'll love to contribute on this part. And also a huge round of applause to @hiteshchoudhary for providing us with this repository, you have been a huge inspiration throughout my growing phase as a developer.

error building docker

[email protected] start
apihub-main-backend-1 | > nodemon -r dotenv/config src/index.js
apihub-main-backend-1 |
apihub-main-backend-1 |
apihub-main-backend-1 | npm ERR! code EACCES
apihub-main-backend-1 | npm ERR! syscall spawn sh
apihub-main-backend-1 | npm ERR!
apihub-main-backend-1 | path /usr/src/freeapi
apihub-main-backend-1 | npm ERR! errno -13
apihub-main-backend-1 | npm ERR! Error: spawn sh EACCES
apihub-main-backend-1 | npm ERR! at ChildProcess._handle.onexit (node:internal/child_process:285:19)
apihub-main-backend-1 | npm ERR! at onErrorNT (node:internal/child_process:483:16)
apihub-main-backend-1 | npm ERR!
apihub-main-backend-1 | at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
apihub-main-backend-1 | npm ERR! Error: spawn sh EACCES
apihub-main-backend-1 | npm ERR!
apihub-main-backend-1 | at ChildProcess._handle.onexit (node:internal/child_process:285:19)
apihub-main-backend-1 | npm ERR! at onErrorNT (node:internal/child_process:483:16)
apihub-main-backend-1 | npm ERR! at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
apihub-main-backend-1 | npm ERR! errno: -13,
apihub-main-backend-1 | npm ERR! code: 'EACCES',
apihub-main-backend-1 | npm ERR! syscall: 'spawn sh',
apihub-main-backend-1 | npm ERR!
apihub-main-backend-1 | path: '/usr/src/freeapi',
apihub-main-backend-1 | npm ERR! spawnargs: [ '-c', 'nodemon -r dotenv/config src/index.js' ],
apihub-main-backend-1 | npm ERR! cmd: 'sh',
apihub-main-backend-1 | npm ERR! args: [ '-c', 'nodemon -r dotenv/config src/index.js' ],
apihub-main-backend-1 | npm ERR! stdout: null,
apihub-main-backend-1 | npm ERR! stderr: null,
apihub-main-backend-1 | npm ERR! event: 'start',
apihub-main-backend-1 | npm ERR! script: 'nodemon -r dotenv/config src/index.js',
apihub-main-backend-1 | npm ERR! pkgid: '[email protected]'
apihub-main-backend-1 | npm ERR! }
apihub-main-backend-1 | npm ERR!
apihub-main-backend-1 | npm ERR! The operation was rejected by your operating system.
apihub-main-backend-1 | npm ERR! It is likely you do not have the permissions to access this file as the current user
apihub-main-backend-1 | npm ERR!
apihub-main-backend-1 | npm ERR!
apihub-main-backend-1 | If you believe this might be a permissions issue, please double-check the
apihub-main-backend-1 | npm ERR!
apihub-main-backend-1 | permissions of the file and its containing directories, or try running
apihub-main-backend-1 | npm ERR! the command again as root/Administrator.

Add items in Cart

@wajeshubham adding items to the cart is not working. show the some Error I want to add any item

=>Error:{
"statusCode": 500,
"data": null,
"success": false,
"errors": [],
"message": "Cannot read properties of null (reading 'items')",
"stack": "TypeError: Cannot read properties of null (reading 'items')\n at
file:///E:/BackEnd/Node%20js/FreeApi_App/apihub/src/controllers/apps/ecommerce/cart.controllers.js:140:29\n at
process.processTicksAndRejections (node: internal/process/task_queues:95:5)"
}

FreeAPI.docs.-.Google.Chrome.2023-09-14.10-50-27.mp4

=> Watch the Video Better Understanding of How to Work Add item in cart

=>user add an item is only one it is not right because the user can multiple item cart

=>user add an item only one it is not right because the user can also add multiple items cart. it is some Problem that can be changed

Hey Sir their seems to b an issue

image

{MongoDB connection error: Error: queryTxt ETIMEOUT cluster0.fphzhgd.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (node:internal/dns/promises:275:17) {
errno: undefined,
code: 'ETIMEOUT',
syscall: 'queryTxt',
hostname: 'cluster0.fphzhgd.mongodb.net'
}
[nodemon] app crashed - waiting for file changes before starting...

i countinously getting this error and app creashed

Refactor: need of a common validator for checking mongo ids in route path variables or inside the body

Describe the issue

Currently, the application utilizes separate validators for each endpoint that requires validation of MongoDB Ids passed within the route path variable (utlized more frequently) or request body (rarely used).

This approach leads to code duplication violating the DRY (Don't Repeat Yourself) principle. The same validation logic is repeated multiple times for different endpoints, causing maintenance overhead and making the codebase less maintainable (may be).

Expected solution

To address this issue and adhere to the DRY principle, it is recommended to create a common validator function that can handle the validation of MongoDB Ids by accepting the id name as a parameter.

This common validator function can be reused across all endpoints where MongoDB Id validation is needed, reducing the redundant code.

Proposed common validator functions

The proposed common validator function should accept an "idName" parameter, which represents the name of the MongoDB Id to be validated in the route path variable or request body. Here's a general outline of the proposed common validator function:

import { body, param } from "express-validator";

/**
 *
 * @param {string} idName
 * @returns ValidationChain[]
 * @description A common validator responsible to validate mongodb ids passed in the url's path variable
 */
const mongoIdPathVariableValidator = (idName) => {
  return [
    param(idName).notEmpty().isMongoId().withMessage(`Invalid ${idName}`),
  ];
};

/**
 *
 * @param {string} idName
 * @returns ValidationChain[]
 * @description A common validator responsible to validate mongodb ids passed in the request body
 */
const mongoIdRequestBodyValidator = (idName) => {
  return [body(idName).notEmpty().isMongoId().withMessage(`Invalid ${idName}`)];
};

Folder structure to be followed

Create a folder named common inside the src/validators folder. Add an index.js file and add proposed validators inside it.

How to use the common validator functions

To validate MongoDB Ids for different endpoints, you can now simply call the mongoIdPathVariableValidator or mongoIdRequestBodyValidator functions with the corresponding idName as a parameter. Here's an example of how to use the common validator function for the three mentioned endpoints:

// Following are the dummy endpoints just for a reference
import {
  mongoIdPathVariableValidator,
  mongoIdRequestBodyValidator
} from "../route.to.validators";
import { validate } from "../../../validators/validate.js"; // validation middleware

// http://localhost:8080/api/v1/users/:userId
router
  .route("/:userId")
  .get(
    mongoIdPathVariableValidator("userId"),
    validate,
    getUserById
  );

// http://localhost:8080/api/v1/orders/place-order
router
  .route("/place-order")
  .post(
    // to place order user needs to select an address from his/her profile. which client will pass in the request body
    mongoIdRequestBodyValidator("addressId"), 
    validate,
    placeOrder
  );

By using the mongoIdPathVariableValidator function, you eliminate the need for separate validator functions for each endpoint and promote code reuse, making the codebase more maintainable and efficient.

Additional context

The proposed solution provides two common validator functions that significantly reduces code duplication and promotes the DRY principle.

By using this common function, you can easily validate MongoDB Ids for different endpoints without repeating the same validation logic.

Additionally, if there are future changes or improvements to be made in the MongoDB Id validation process, you only need to modify the common validator function, and the changes will automatically apply to all endpoints that use it.

Let's discuss before starting the implementation 🚀

FEATURE: Add single vendor e-commerce admin panel backend api

Describe the Feature

Features list of single vendor e-commerce admin panel application

  • Dashboard
  • Sub admin manager
  • Users list
  • Order management
  • Delivery boy management
  • Coupon management
  • Earning management
  • Stock management
  • Notification manager
  • Report manager
  • Static content manager
  • Email template manager
  • Global settings

Use Case

1. Dashboard:

  • View Dashboard: Admins can access a centralized dashboard displaying key metrics and insights about the e-commerce platform's performance, including sales revenue, order volume, and customer engagement metrics.

2. Sub Admin Manager:

  • Create Sub Admin: Admins can create new sub-administrator accounts with specific roles and permissions tailored to their responsibilities.
  • Manage Sub Admins: Admins can view, edit, and deactivate existing sub-administrator accounts, adjusting their permissions and access levels as needed.

3. Users List:

  • View User List: Admins can access a list of registered users on the platform, including their contact information, order history, and account status.
  • Search and Filter Users: Admins can search for specific users and apply filters to narrow down the user list based on criteria such as registration date or geographic location.

4. Order Management:

  • View Orders: Admins can view a list of all orders placed by customers, including order details, customer information, and current status.
  • Update Order Status: Admins can update the status of orders as they progress through the fulfillment process, such as marking orders as confirmed, shipped, or delivered.
  • Manage Returns and Refunds: Admins can handle customer requests for returns and refunds, processing refunds and updating inventory accordingly.

5. Delivery Boy Management:

  • Assign Delivery Boys: Admins can assign delivery personnel to specific orders for fulfillment, tracking the status of each delivery and managing delivery schedules.
  • Monitor Delivery Performance: Admins can track the performance of delivery personnel, including metrics such as delivery times and customer satisfaction ratings.
  • Manage Delivery Zones: Admins can define and manage delivery zones, specifying geographic areas where orders can be delivered and assigning delivery personnel accordingly.

6. Coupon Management:

  • Create Coupons: Admins can create discount coupons and promotional codes for use by customers during checkout, specifying details such as discount amount, expiration date, and usage limits.
  • Track Coupon Usage: Admins can monitor the usage of coupons, tracking metrics such as redemption rates and revenue generated through coupon campaigns.
  • Manage Coupon Campaigns: Admins can organize and manage multiple coupon campaigns, scheduling promotions and targeting specific customer segments.

7. Earning Management:

  • View Earnings: Admins can view detailed reports of earnings generated through sales, commissions, and other revenue streams.
  • Track Affiliate Earnings: Admins can track earnings generated by affiliate marketers and other partners, managing payouts and commissions.
  • Generate Earning Reports: Admins can generate reports summarizing earnings over specific time periods, facilitating financial analysis and decision-making.

8. Stock Management:

  • Manage Inventory: Admins can track and manage product inventory levels, adjusting stock quantities and receiving alerts for low stock levels.
  • Handle Stock Replenishment: Admins can initiate stock replenishment processes, such as placing orders with suppliers or transferring inventory between warehouses.
  • Monitor Stock Movement: Admins can track stock movements and adjustments, including sales, returns, and damaged goods.

9. Notification Manager:

  • Send Notifications: Admins can send notifications to customers, delivery personnel, and other stakeholders via email, SMS, or push notifications.
  • Manage Notification Templates: Admins can create and customize notification templates for different types of messages, such as order confirmations, shipping updates, and promotional announcements.
  • Schedule Automated Notifications: Admins can schedule automated notifications to be sent at specific times or triggered by predefined events, such as order fulfillment or product restocks.

10. Report Manager:

  • Generate Reports: Admins can generate various reports summarizing key performance metrics and business insights, such as sales reports, inventory reports, and customer analytics.
  • Customize Report Parameters: Admins can customize report parameters and filters to generate tailored reports based on specific criteria and time periods.
  • Export Reports: Admins can export reports in different formats (e.g., PDF, CSV) for further analysis or sharing with stakeholders.

11. Static Content Manager:

  • Manage Static Pages: Admins can create and edit static pages such as About Us, FAQ, and Terms of Service, managing the content and layout of each page.
  • Publish Content Updates: Admins can publish updates to static pages, ensuring that the information displayed to customers is accurate and up-to-date.
  • Control Page Visibility: Admins can control the visibility of static pages, determining which pages are accessible to customers and which are hidden or restricted.

12. Email Template Manager:

  • Customize Email Templates: Admins can customize email templates for automated communications sent to customers, such as order confirmations, password resets, and promotional emails.
  • Preview Email Templates: Admins can preview email templates to ensure that they are formatted correctly and contain the desired content before sending.
  • Manage Template Versions: Admins can manage multiple versions of email templates, enabling A/B testing and iterative improvements to email communications.

13. Global Settings:

  • Configure Platform Settings: Admins can configure global settings and preferences for the e-commerce platform, such as currency, language, and tax settings.
  • Manage Payment and Shipping Options: Admins can configure payment gateways, shipping carriers, and other integrations, customizing settings to meet business requirements.
  • Control Platform Policies: Admins can define and enforce platform policies, such as return policies, privacy policies, and terms of service, ensuring compliance with legal and regulatory requirements.

Additional Information

No response

Suggested Tools

  • Node JS
  • MongoDB
  • Express JS
  • Api Testing [Postman]
  • Api formating [Swgger]

Additional Context or Information

No response

FEATURE: Add more youtube backend api

Describe the Feature

features list of you tube video application

  • upload video
  • delete video
  • update video file
  • watch video
  • get user liked videos
  • add comment on videos
  • get all comment on videos
  • get liked videos
  • get subscribed channels
  • add small tweet section
  • toggle like on video
  • toggle subscribed on video channel
  • likes on video comment
  • create video Playlist
  • removed playlist videos
  • update video playlist
  • get channel statictis information

Use Case

help to beginners

help to lot of people they not able pay youtube video api and they want to create a video app

Additional Information

@hiteshchoudhary
hello everyone

I want to contribute video API features.
plese assign video api task me

Suggested Tools

technologies

  1. Node js
  2. Express js
  3. Mongodb
  4. Api Testing [Postman]
  5. Api formating [Swgger]

Additional Context or Information

No response

BUG: bcrypt.js

Describe the bug

does not export default

To Reproduce

No response

Expected behavior

No response

Screenshots

Screenshot 2024-03-12 211501

OS

Windows

OS Version

11

Client

chrome

Additional context or Information

No response

FRONTEND: Status Code Insight

Frontend App Title

statuscodes

Overview

To offer users a comprehensive understanding of various HTTP status codes.

Technologies to be Used

  • React.js: A JavaScript library for building user interfaces.
  • Shadcn: A collection of open-source UI components and tools for building web applications.
  • Tailwind CSS: A utility-first CSS framework for rapidly building custom designs.
  • Zustand: A state management library for React applications.

Detailed Features

1. Code Lookup:

  • Users can input any numerical HTTP status code.
  • The app provides instant details about the code.

2. Detailed Explanations:

  • For each status code, the app explains its purpose.
  • Common usage scenarios are described to provide context.

3. Elegant User Interface:

  • A clean, intuitive UI that makes navigation and reading easy.
  • Visual elements like color-coding or icons to represent different categories of status codes (e.g., 2xx for success, 4xx for client errors).

4. Search and Filter:

  • Users can search for specific codes or filter codes by categories (Informational, Success, Redirection, Client Error, Server Error).

5. Examples and Case Studies:

  • Real-world examples or case studies to show how particular status codes are used in practice.
    Interactive Learning Tools:
  • Quizzes or flashcards for users to test their knowledge of HTTP status codes.

6. Regular Updates:

  • The app updates the latest status codes and information as the HTTP protocol evolves.

Tech Stack Used

ReactJs, Zustand, tailwindCss, Shadcn

Built For Platform

web

Project Path

$ROOT_FOLDER/examples/kitchen-sink/statuscodes/web/react-shadcn-tailwind-zustand

BUG: Coupons can be created in past date.

Describe the bug

Hi, I just found out that coupons creation endpoint in coupon controllers has a bug, that it accepts startData and expiry date both as of past. Which I think should not be the case.

To Reproduce

Just create a coupon with startDate and expiryDate in the past.

Expected behavior

Coupons will be created.

Screenshots

image

OS

Windows 11

OS Version

22H2

Client

Postman

Additional context or Information

No response

feat: social media app web frontend

Social Media Web App

Overview

To develop a social media web application using React.js ( with typescript ), Shadcn, Tailwind CSS, and React Redux.

Technologies to be Used

  • React.js: A JavaScript library for building user interfaces.
  • Shadcn: A collection of open-source UI components and tools for building web applications.
  • Tailwind CSS: A utility-first CSS framework for rapidly building custom designs.
  • React Redux: A state management library for React applications.

Features

  • User Authentication: Implement a secure user authentication system to allow users to create accounts and log in.
  • Profile Pages: Enable users to customize their profiles, add profile pictures, and update personal information.
  • Post Creation and Interaction: Implement the ability for users to create posts, comment on posts, and like posts.
  • Responsive Design: Ensure the web app is responsive and accessible across various devices.

CORS issue after my own deployment on Railway [ Vue JS ]

Describe the bug

My application was successfully deployed and I got the following URL

https://freeapi-app-production-a55c.up.railway.app/

I'm trying to fetch the todos by following link

https://freeapi-app-production-a55c.up.railway.app/api/v1/todos

But it is giving me corse issue

Just to be clear I'm using Vue js on frontend side ( Vite Template )

To Reproduce

No response

Expected behavior

No response

Screenshots

Error Screenshot
image

Code:

image

OS

No response

OS Version

No response

Client

No response

Additional context or Information

I'm not used to open source pardon me please if I made any mistake

Thank you

FRONTEND: Random Products Flutter App

Frontend App Title

Random Products Flutter App

Overview

The Random Products App will be built using flutter, and will allow users to browse the different products.

Detailed Features

  1. Home Page - The home page will consist of random products from the API, along with their brand name and a thumbnail.
  2. Product Details Page - The product details page will show the product in detail, along with carousel slider for viewing the images, along with its price, rating and an indicator if the stock of the product is close to ending.
  3. Search Page - the search bar will allow the users to search for a product, and they will be able to see results for their queries.

Tech Stack Used

Flutter, Provider

Built For Platform

mobile

Project Path

$ROOT_FOLDER/examples/public/randomproducts/mobile/flutter-provider

Why no typescript?

I have a question
Why this project is built with javascript as more projects are adopting typescript why are we not using the same here.
Just for the question.

Refactor: Refrain from Immediate Invocation of Middleware Functions in Route Definitions

In the file located at /src/routes, a subtle issue has been identified regarding the usage of middleware functions in route definitions. The middleware function, such as userForgotPasswordValidator, is being invoked with parentheses, potentially leading to unexpected behavior. It is recommended to pass middleware functions as references without immediate invocation, aligning with best practices.

Steps to Reproduce:
1- Navigate to /src/routes.
2- Inspect the specific route definitions.
3- Observe that middleware functions like userForgotPasswordValidator are invoked with parentheses.

Expected Result:
Middleware functions should ideally be passed as references without immediate invocation when defining routes to ensure proper execution during the request-response cycle. As per the Express.js documentation: Middleware are functions that have access
to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle.

Express.js Documentation: https://expressjs.com/en/guide/writing-middleware.html#:~:text=Middleware%20functions%20are%20functions%20that,middleware%20succeeding%20the%20current%20middleware

Screenshot from 2024-01-03 23-17-10

Actual Result:
The middleware functions are invoked with parentheses during route definition.
Screenshot from 2024-01-03 23-31-34

Middleware functions often rely on dynamic behavior based on the request context, such as extracting data from the request object. When invoked immediately, these functions may not have access to the request object and may not behave as expected and Invoking the middleware immediately may skip the error-handling logic during route definition.

Relevant Context:
This observation is made within the context of Express.js routing. Invoking middleware functions with parentheses during route definition, even for seemingly small issues, can potentially lead to unforeseen challenges, as middleware functions are designed to execute dynamically during the request-response cycle.

Actual Example:

router
  .route("/forgot-password")
  .post(userForgotPasswordValidator(), validate, forgotPasswordRequest);

Expected Example:

router
  .route("/forgot-password")
  .post(userForgotPasswordValidator, validate, forgotPasswordRequest);

Contributor's Note:
I am interested in addressing this issue and plan to work on a solution. I would appreciate any feedback or additional guidance from maintainers and the community as I proceed with the resolution.

FEATURE: Comprehensive Documentation Guide for the FreeAPI Project

Describe the Feature

We propose enhancing our open-source project by implementing a comprehensive documentation guide for the overall FreeAPI project. This feature request aims to provide users and developers with clear, detailed, and accessible documentation to facilitate easier understanding, implementation, and contribution to the project.

The documentation guide should cover all aspects of the API, including but not limited to:

  • Complete API contract covering all endpoint descriptions and usage.
  • Request and response formats.
  • Authentication methods and requirements.
  • Rate limiting and usage policies.
  • Error handling and troubleshooting guidelines.
  • Code examples and sample application showcasing from the frontend contributions.
  • The documentation should be regularly updated to reflect any changes or enhancements made to the API or the project as a whole.
  • Consider incorporating interactive elements such as code snippets, API explorers, and tutorials to enhance user engagement and learning experience.
  • Additional tips and tricks section for developers not only related to FreeAPI but overall software development

Use Case

Imagine a scenario where a new developer or user wants to integrate our API into their project, right now the README.md file provides detailed understanding of the setup and overall project. However, with a comprehensive documentation guide readily available, they can quickly understand the functionalities, endpoints, parameters, authentication methods, and usage examples. This streamlined process encourages adoption and fosters a positive user experience.

Additional Information

No response

Suggested Tools

We would love to hear from the community if there are any tools available to make this process smooth, more easy and fast.

Additional Context or Information

No response

FEATURE:Would like to add a edit message controller in Chat-app Backend and would like to add the delete message option in the official frontend of the chat app

Describe the Feature

Would like to add a edit message endpoint in the backend of the chat-app and also would like to add the delete message feature in the frontend in the official frontend of the chat-app .
@wajeshubham

Use Case

User can edit the message they have sent in group chat and one to one chat only messages not attachments

Additional Information

Would like to add the delete message feature in the frontend for user to be able to delete the message will modify the frontend code that is written in react-tailwind that is present in the repo.

Suggested Tools

No response

Additional Context or Information

No response

FEATURE: Would like to add Few more controllers or API's to the Chat-app

Describe the Feature

I am proposing to add more controllers or API function in the chat-app

I want to add
1.Delete a single message or attachment in one to one chat within 15 mins of creation of the message
2.Upload group Picture by the admins
3.Upload description of groups by the admins
4.Editting the group picture or group description by the admins
5.Deleting messages in a group by the sender within 15 minutes of sending
6.Creating different types of group where only admins can send the messages and attachments and participants can see

Use Case

This will enhance the chat app experience for the users and also improve the functionality of the chat app like in the professional apps like whatsapp.

Additional Information

@hiteshchoudhary
I would like to start working on the additional api's in the chat app i was trying to make my own chat-app with free api but found those functionalities missing so i would like to add them .

Suggested Tools

Technologies
No additional technologies other than those that are already being used

Additional Context or Information

No response

ENHANCEMENT: Public api performance Improvement

Describe the enhancement

In order to pointout the getPublics method (book,cat,dog,meal,randomjoke,randomproduct,stock), we perform data filtering through search key processing. Upon discovering included keys in the query parameters, we proceed with the entire filterout process and eliminate the keys. Alternatively, we can obtain the paginated payload first, which can greatly enhance performance, and then remove the key.

Use Case

No response

Additional Information

suggested solution but there can be more cleaner solution just pointing out this we can process lot less data for removing keys

let booksArray = query
    ? structuredClone(booksJson).filter((book) => {
        return (
          book.searchInfo?.textSnippet.toLowerCase().includes(query) ||
          book.volumeInfo.title?.includes(query) ||
          book.volumeInfo.subtitle?.includes(query)
        );
      })
    : structuredClone(booksJson);

//if (inc && inc[0]?.trim()) {
// booksArray = filterObjectKeys(inc, booksArray);
//}
const paginatedResponse = getPaginatedPayload(booksArray, page, limit)
  const updatedBooks = inc
    ? filterObjectKeys(inc, paginatedBooks.data)
    : paginatedBooks.data;
  return res.status(200).json(
    new ApiResponse(
      200,
      {
        ...paginatedBooks,
        data: updatedBooks,
      },
      "Books fetched successfully"
    )
  );
});

Suggested Tools

No response

Additional Context or Information

Hopefully i submitted issue right way if not please let me know and if provided info is right , i can work on this enhancement

FEATURE: Logging Enhancement Proposal

Describe the Feature

I propose the implementation of comprehensive logging for the FreeAPI backend project. The logging should cover both normal application-level logs and detailed API call logs. (Application level logs can be centralized by injecting logger into the error middleware as that is the central place where the errors are being handled)

IMPORTANT:

Our emphasis is not on complex logging by logging each line in the application but rather on strategic logging:

  • HTTP API Call Logs: To be implemented using something like Morgan middleware in the app.js
  • Application-Level Error Logs: To be implemented in the error middleware of FreeAPI, the central place for handling errors with informative messages.

Use Case

This enhancement aims to improve the overall observability and debugging capabilities of the FreeAPI backend. With centralized logging, we can efficiently track application activities, monitor errors, and gain insights into API interactions.

Additional Information

Implementing a centralized Morgan middleware for HTTP API calls and integrating Winston for application-level logs can greatly enhance our ability to track, analyze, and troubleshoot issues efficiently.

Suggested Tools

Winston (for application-level logs):

  • A versatile and customizable logging library for Node.js.
  • Offers support for multiple transports (console, file, etc.).
  • Allows log level configuration for different environments.

Morgan (for API call logging):

  • Middleware for Express.js to log HTTP requests and responses.
  • Can be customized to log specific details, such as status codes, request methods, and response times.
  • Helps in centralizing API call logs for better analysis and monitoring.

Additional Context or Information

Priority:

Medium

Effort Estimate:

Approximately 2-3 days for implementation and integration.

Purpose:

Centralized logging will streamline error handling and provide valuable insights into the FreeAPI backend's behavior. This enhancement aligns with the project's goal of maintaining a robust and easily maintainable codebase.

Contributions are welcome

If you're interested in contributing to the implementation of this feature, feel free to let us know!

Improvement of UI

I want to improve the UI design of the project as it's currently not looking cool so I want to do some changes in front end to make page minimal.

Thanks

FEATURE: Implement URL Access Controller for Enhanced Security and Access Control

Describe the Feature

The URL Access Controller is a new feature aimed at enhancing the security and access control of our application. It allows us to manage and enforce access permissions for specific URLs within our system, ensuring that only authorized users can access certain resources.

Key Functionality:

  • Access Control: The URL Access Controller provides granular control over which users or user groups can access specific URLs within our application.
  • Security By enforcing access control at the URL level, we can prevent unauthorized access to sensitive parts of our application, enhancing overall security.

Use Case

No response

Additional Information

No response

Suggested Tools

  • External Package Integration: We've leveraged an external package to implement the URL Access Controller, ensuring reliability and adherence to best practices.

Additional Context or Information

No response

user profile details problem

how can i retrieve user details like the username,email id..as the endpoint http://localhost:8080/api/v1/ecommerce/profile gives a JSON data like

{
  "statusCode": 200,
  "data": {
    "_id": "6590486f1b1bfe2255627e21",
    "firstName": "John",
    "lastName": "Doe",
    "countryCode": "",
    "phoneNumber": "",
    "owner": "6590486e1b1bfe2255627e1c",
    "createdAt": "2023-12-30T16:42:23.248Z",
    "updatedAt": "2023-12-30T16:42:23.248Z",
    "__v": 0
  },
  "message": "User profile fetched successfully",
  "success": true
}

now from here how can i fetch the details from the owner Id......as there is no endpoint to fetch details from there

FRONTEND: Online platform to sell old things

Frontend App Title
E-Shopify

Overview
E-Shopify is a modern online shopping platform built using React.js and Tailwind CSS, offering a sleek and intuitive user interface for seamless shopping experiences.

Detailed Features
User Authentication:

Users can easily register accounts or log in securely to access personalized features and track their orders.
Product Discovery:

Comprehensive search and filter options enable users to discover products effortlessly based on categories, brands, or specifications.
Shopping Cart Management:

Intuitive cart functionality allows users to add, remove, or update items, ensuring a smooth and convenient shopping experience.
Secure Checkout Process:

Multiple payment gateways ensure secure transactions, providing users with various options to complete their purchases with confidence.
Order Tracking:

Users can track their orders in real-time, receiving updates on order status and delivery information for enhanced transparency.
Tech Stack Used
Frontend Framework: React.js
Styling: Tailwind CSS
Built For Platform
E-Shopify is optimized to run on various platforms, providing flexibility and scalability. Hosting options include services like Vercel, Netlify, or traditional web hosting providers.

E-Shopify offers a seamless online shopping experience, combining the power of React.js for dynamic user interfaces and Tailwind CSS for elegant and responsive designs. With its user-friendly features and robust functionality, E-Shopify ensures a delightful shopping journey for every customer.

FRONTEND: Ecommerce website using Next.js

Frontend App Title

HMart

Overview

I would like build an ecommerce application using next.js.

Frameworks:

  • Next.js(TypeScript) - to use the power of different rendering techniques.
  • axios - for fetching
  • React Query - for state management
  • tailwindcss - for styling
  • shadcn - for components
  • tabler icons - icons package
  • playwright - for e2e testing

Detailed Features

I would like to develop a user friendly e commerce website.

  • User can create and login to their accounts.
  • Search and filter functionality for the users.
  • User can browse, add/remove items from the cart and purchase items based on the selected payment methods.
  • Create a CMS page for the ADMIN

Tech Stack Used

Next.js, React Query

Built For Platform

The frontend will run on vercel

Project Path

examples/apps/ecommerce/nextjs-ts-react-query-playwright

Bug in your website

Unable to reach the Doc and Setup video through the website .
Here I can't able to get the Cooked in Docs and Setup Video
Capture12

These Cooked in Docs , Setup video and Featured buttons are not working correctly ......

Please click it to check whether it's working or not

BUG not able to hit get request for "my profile" in ecommerce app. Response is 401 not authorized, but parameters are not taking any user related input.

Describe the bug

BUG not able to hit get request for "my profile" in ecommerce app. Response is 401 not authorized, but parameters are not taking any user related input.
A clear and concise description of what the bug is.

To Reproduce

go to swagger, ecommerce, get /ecommerce/profile -> returning not authorized as response
Steps to reproduce the behavior:

Expected behavior

A clear and concise description of what you expected to happen.

Screenshots

If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Client [e.g. postman, thunder client, chrome, safari]
  • Version [e.g. 22]

Additional context

Add any other context about the problem here.

FEATURE: Order Return Request Controller Should be there in this repo

Describe the Feature

Return Request Controller not there
and also in orderModels currentStatus is should be there
currentStatusEnum = ["PENDING" , "SHIPED" , "DELEVERED" , "CENCELLED"]

Use Case

No response

Additional Information

No response

Suggested Tools

No response

Additional Context or Information

No response

BUG Potential Security Issue: Sensitive User Information Exposed

Describe the bug

The searchAvailableUsers function in chat.controller.js is currently returning all fields of the user documents from the database, which might include sensitive information. This could potentially lead to a security issue.

To Reproduce

Steps to reproduce the behavior:

  1. Call the searchAvailableUsers function.
  2. Observe the returned user data.

Expected behavior

The function should exclude sensitive fields when querying the database. For instance, if the User schema includes a password field, it should not be sent to the client. This can be achieved by adding a $project stage to the aggregation pipeline to exclude these fields.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Client [e.g. postman, thunder client, chrome, safari]
  • Version [e.g. 22]

Additional context

Here's the function in question:

const searchAvailableUsers = asyncHandler(async (req, res) => {
  const users = await User.aggregate([
    {
      $match: {
        _id: {
          $ne: req.user._id, // avoid logged in user
        },
      },
    },
  ]);

  return res
    .status(200)
    .json(new ApiResponse(200, users, "Users fetched successfully"));
});

[enhancement]: Migration to TypeScript

Background

Right now FreeApi.app is completely written is JavaScript. TypeScript has become an industry standard nowadays. Having the codebase migrated to TypeScript will benifit the developers to better understand the codebase. TypeScript will benifit the project with better type-safety and tooling and thus it will result in improved code quality and confidence in code refactor.

Plan

To incrementally migrate to TypeScript because of it's type-safety and tooling. We can have a discussion below for any better alternatives or reasons as to why not to migrate to TypeScript at all.

Outcome

  1. Improved code quality
  2. Avoid unnecessary common bugs
  3. Confidence to refactor the codebase
  4. Better IDE/Text Editor Code completion
  5. Better readability of the codebase

Note

I'm not suggesting complete rewrite of the codebase but incremental adoption of TypeScript.
If possible kindly leave this issue open for discussion.

BUG: Address Not Found after deleting it in orders.

Describe the bug

Hi, I just found out a use case.
Suppose a user place an order with a specific address (represented by an address object's Mongoose ID). Later, if the user deletes that address and then fetches the order again, the order should still display the original address details associated with that address ID at the time the order was placed, rather than showing the updated address details if the address was later modified.

To Reproduce

Just create an order, and delete address that was used for that order, and fetch the same order again by ID

Expected behavior

The very first details with which order was placed must be given in the response.
Thanks!

Screenshots

No response

OS

All

OS Version

No response

Client

Postman

Additional context or Information

No response

BUG AuthContext values (token and user) are null in PrivateRoute component

Description:

Upon successful login, the user is correctly redirected to the /chat route. However, if the user manually changes the URL to /login and then attempts to navigate back to /chat, the PrivateRoute component prevents this navigation. This behavior occurs because the token and user values in AuthContext are null for an instance, causing the PrivateRoute component to redirect the user as if they were not authenticated.

Steps to reproduce:

  1. Log in successfully, which redirects to the /chat route.
  2. Manually change the URL to /login.
  3. Attempt to navigate back to /chat.

Expected behavior:

The user should be able to navigate to /chat after step 3 since they are already authenticated.

Actual behavior:

The PrivateRoute component prevents navigation to /chat because it reads token and user as null.

Additional context:

Error: Cannot find module '/usr/src/freeapi/prepare.js'

Describe the bug

Error in Dockerfile configuration after including prepare.js script for commit-lint.

The issue is due to the absence of prepare.js file for node prepare.js command which runs after the package installation step while building the docker image.

However, while running the prepare command docker hasn't cloned the ROOT directory which leads to absence of prepare.js.

proposed solution

prepare.js file must be available quickly after the package installation step in the Dockerfile.

Additional context

Error logs:

$ node prepare.js
#0 27.57 node:internal/modules/cjs/loader:1093
#0 27.57   throw err;
#0 27.57   ^
#0 27.57 
#0 27.57 Error: Cannot find module '/usr/src/freeapi/prepare.js'
#0 27.57     at Module._resolveFilename (node:internal/modules/cjs/loader:1090:15)
#0 27.57     at Module._load (node:internal/modules/cjs/loader:934:27)
#0 27.57     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
#0 27.57     at node:internal/main/run_main_module:23:47 {
#0 27.57   code: 'MODULE_NOT_FOUND',
#0 27.57   requireStack: []
#0 27.57 }
#0 27.57 
#0 27.57 Node.js v19.8.1
#0 27.60 error Command failed with exit code 1.
#0 27.61 info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
------
failed to solve: process "/bin/sh -c yarn install --pure-lockfile" did not complete successfully: exit code: 1

Complex chat app error- vite is not an internal and external command

F:\apihub-main\apihub-main\examples\apps\chat-app\web\react-vite-tailwind>npm run dev

[email protected] dev
vite

'vite' is not recognized as an internal or external command,
operable program or batch file. While following the steps to learn socket.io from freeapi project taught by hitesh sir in english youtube channel, I m getting this thing again and again. Do I need to install the vite again separately? Kindly help anyone.

The deployment is crashing in Docker and NPM

Describe the bug

The App deployment is crashing in both NPM and Docker

To Reproduce

Clone the repo
Try to open using Docker

Expected behavior

The server should boot up

Screenshots

If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: Mac OS
  • Client : VS Code
  • Version [e.g. 22]

Additional context

Add any other context about the problem here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.