Skip to content

🌐 MERN backend template for e-commerce websites

License

Notifications You must be signed in to change notification settings

roblzs/e-commerce-backend

Repository files navigation

e-commerce backend

🌐 MERN backend template for e-commerce websites

How to run locally

  1. Download node from here
  2. Download git from here
  3. Install yarn npm install --global yarn
  4. Get source code git clone https://github.com/RobzLegz/e-commerce-backend backend
  5. cd backend
  6. Install dependencies yarn install
  7. Create .env file touch .env
  8. Update .env file
PORT=
MONGODB_URL=
REFRESH_TOKEN_SECRET=
ACCESS_TOKEN_SECRET=
CLOUD_NAME=
CLOUD_API_KEY=
CLOUD_API_SECRET=

PORT can be a random 4 digit number, I'd suggest 5000

Create a mongodb project by following this tutorial and update MONGODB_URL in .env file

You can create REFRESH_TOKEN_SECRET and ACCESS_TOKEN_SECRET by generating secure 50 character password here

CLOUD_NAME & CLOUD_API_KEY & CLOUD_API_SECRET are accessible when You register to cloudinary

  1. run project yarn dev

API routes

app.use("/api/user", userRouter); //http://localhost:5000/api/user
app.use("/api/categories", categoryRouter); //http://localhost:5000/api/categories
app.use("/api/upload", uploadRouter); //http://localhost:5000/api/upload
app.use("/api/products", productRouter); //http://localhost:5000/api/products
app.use("/api/orders", orderRouter); //http://localhost:5000/api/orders

Order handling

const {name, email, phoneNumber, products, address, city, date} = req.body;
if(!name || !email || !phoneNumber || !products || !address || !city || !date){
    return res.status(400).json({err: "Please fill in all fields"});
}

let total = 0;
let soldProductIds: string[] = [];

products
    .filter((product: Product) => !soldProductIds.includes(product._id))
    .forEach((product: Product) => {
        if(!soldProductIds.includes(product._id)){
            let quantity = products.filter((p: Product) => p._id === product._id).length;
            total += (product.price * quantity);
            soldProductIds.push(product._id);
            sell(product._id, quantity, product.sold, product.stock);
        }
    });

const newOrder = new Orders({
    name, 
    email, 
    phoneNumber, 
    products, 
    address, 
    city, 
    date, 
    total
});

await newOrder.save();

res.json({msg: "Order received, check Your email"});
const sell = async (id: string, quantity: number, oldSold: number, oldStock: number) => {
    let newSold = oldSold + quantity;
    let newQuantity = oldStock - quantity;

    await Products.findByIdAndUpdate({_id: id}, {
        sold: newSold,
        stock: newQuantity,
    });
}

About

🌐 MERN backend template for e-commerce websites

Resources

License

Stars

Watchers

Forks