Skip to content

Commit

Permalink
Products
Browse files Browse the repository at this point in the history
  • Loading branch information
swarnendu19 committed Mar 24, 2024
1 parent 18e70b8 commit a121ad1
Show file tree
Hide file tree
Showing 5 changed files with 140 additions and 24 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

.env
node_modules
dist
dist-ssr
Expand Down
29 changes: 15 additions & 14 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@
"author": "",
"license": "ISC",
"dependencies": {
"@types/validator": "^13.11.9",
"dotenv": "^16.4.5",
"express": "^4.18.3",
"mongoose": "^8.2.1",
"express": "^4.19.1",
"mongoose": "^8.2.2",
"node-cache": "^5.1.2",
"validator": "^13.11.0"
},
"devDependencies": {
"@types/express": "^4.17.21",
"@types/validator": "^13.11.9",
"nodemon": "^3.1.0"
}
}
20 changes: 13 additions & 7 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
import express from "express"; // Import Express module
import userRoute from "./routes/user.js"; // Assuming user.js is in a subfolder named routes
import express from "express";
import NodeCache from "node-cache"
import bodyParser from "body-parser"

const app = express(); // Create an Express application instance
const app = express();


export const myCache = new NodeCache

app.get("/", (req, res) => { // Route handler for the root path ("/")
res.send("API is working with api/v1"); // Send a response message
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", (req, res) => {
res.send("API is working with api/v1");
});


import userRoute from "./routes/user.js";
import orderRoute from "./routes/order.js"

app.use("/api/v1/user", userRoute); // Mount the user routes at the specified path
app.use("/api/v1/user", userRoute);
app.use("/api/v1/order", orderRoute);

export {app}
108 changes: 108 additions & 0 deletions src/controllers/product.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { myCache } from "../app.js";
import { Product } from "../models/produc.js";
import { ApiError } from "../utils/ApiError.js";
import { asyncHandler } from "../utils/asyncHandler.js";
import { NewUserRequestBody } from "../types/types.js";
import { Request } from "express";
import {rm } from "fs"
import { invalidateCache } from "../utils/features.js";


export const getlatestProducts = asyncHandler(async (req, res, next) => {
let products;

if (myCache.has("latest-products"))
products = JSON.parse(myCache.get("latest-products") as string);
else {
products = await Product.find({}).sort({ createdAt: -1 }).limit(5);
myCache.set("latest-products", JSON.stringify(products));
}

return res.status(200).json({
success: true,
products,
});
});

export const getAllCategories = asyncHandler(async (req, res, next) => {
let categories;

if (myCache.has("categories"))
categories = JSON.parse(myCache.get("categories") as string);
else {
categories = await Product.distinct("category");
myCache.set("categories", JSON.stringify(categories));
}

return res.status(200).json({
success: true,
categories,
});
});

export const getAdminProducts = asyncHandler(async (req, res, next) => {
let products;
if (myCache.has("all-products"))
products = JSON.parse(myCache.get("all-products") as string);
else {
products = await Product.find({});
myCache.set("all-products", JSON.stringify(products));
}

return res.status(200).json({
success: true,
products,
});
});

export const getSingleProduct = asyncHandler(async (req, res, next) => {
let product;
const id = req.params.id;
if (myCache.has(`product-${id}`))
product = JSON.parse(myCache.get(`product-${id}`) as string);
else {
product = await Product.findById(id);

if (!product) return next(new ApiError(404,"Product Not Found"));

myCache.set(`product-${id}`, JSON.stringify(product));
}

return res.status(200).json({
success: true,
product,
});
});

export const newProduct = asyncHandler(
async(req: Request<{}, {}, NewUserRequestBody>, res, next)=>{
const { name, price, stock, category } = req.body;
const photo = req.file;

if(!photo) throw new ApiError(400, "Please add photo")

if(!photo || !price || !stock || !category){
rm(photo.path, ()=>{
console.log("Deleted");

})
throw new ApiError(400, "Abe Sare Fields Dal ", 400)
}

await Product.create({
name,
price,
stock,
category: category.toLowerCase(),
photo: photo.path,
})

invalidateCache({product: true, admin: true})

return res.status(201).json({
success: true,
message: "Product Created Successfully"
})

}
)

0 comments on commit a121ad1

Please sign in to comment.