Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/update upload image #4

Open
wants to merge 6 commits into
base: Part_1_Shoe_Store
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 0 additions & 10 deletions env

This file was deleted.

14 changes: 13 additions & 1 deletion package-lock.json

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

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.5.0",
"file-saver": "^2.0.5",
"firebase": "^9.9.4",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-scripts": "5.0.1",
"react-scripts": "^5.0.1",
"swiper": "^8.4.5",
"web-vitals": "^2.1.4"
},
Expand Down
14 changes: 14 additions & 0 deletions server/Utils/multerConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import multer from "multer";
// Cấu hình nơi lưu trữ file
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "uploads/"); // Thư mục lưu file
},
filename: (req, file, cb) => {
const uniqueSuffix = `${Date.now()}-${file.originalname}`;
cb(null, uniqueSuffix); // Tạo tên file duy nhất
},
});

const upload = multer({ storage });
export default upload;
27 changes: 22 additions & 5 deletions server/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,46 @@ import mongoose from "mongoose";
import cors from "cors";
import dotenv from "dotenv";
import userRoutes from "./routes/users.js";
import adminRoutes from "./routes/adminRoute.js";
import shoesPageRoutes from "./routes/productRoute.js";
import morgan from "morgan";
import cookieParser from "cookie-parser";
import { fileURLToPath } from "url";
import multer from "multer";
import path from "path";
import fs from "fs";

const app = express();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
console.log("🚀 ~ __dirname:", __dirname);
app.use(cookieParser());

dotenv.config();
app.use(bodyParser.json({ limit: "30mb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "30mb", extended: true }));
app.use(cors(
{
app.use(
cors({
origin: "http://localhost:3000",
credentials: true,
exposedHeaders: ["set-cookie"],
}
));
})
);
app.use(morgan("dev"));
app.use("/user", userRoutes);
app.use("/admin", adminRoutes);
app.use("/shoesPage", shoesPageRoutes);
app.use("/uploads", express.static(path.join(__dirname, "uploads")));
app.get("/", (req, res) => {
res.send("Hello this is Shoes Store");
});

const uploadFolder = path.join("/", "..", "uploads");
if (!fs.existsSync(uploadFolder)) {
fs.mkdirSync(uploadFolder);
}
// Cấu hình multer

const PORT = process.env.PORT || 5000;

mongoose
Expand All @@ -35,6 +52,6 @@ mongoose
useUnifiedTopology: true,
})
.then(() => app.listen(PORT, console.log(`Server running ${PORT}`)))
.catch(error => console.log(error));
.catch((error) => console.log(error));

export default app;
71 changes: 57 additions & 14 deletions server/controller/productController.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,24 @@ export const getproductPage = async (req, res) => {
try {
req.query.page = parseInt(req.query.page);
req.query.limit = parseInt(req.query.limit);
const features = new APIfeatures(productModel.find(), req.query).sorting().paginating().filtering()
const features = new APIfeatures(productModel.find(), req.query).sorting().paginating().filtering();
const data = await features.query;
const paginateRemaining = features.paginate;
const runnning = await productModel.find(features.queryString).find({ shoeFor: "Running" }).skip(paginateRemaining.skip).limit(paginateRemaining.limit);
const lounging = await productModel.find(features.queryString).find({ shoeFor: "Lounging" }).skip(paginateRemaining.skip).limit(paginateRemaining.limit);
const everyday = await productModel.find(features.queryString).find({ shoeFor: "Everyday" }).skip(paginateRemaining.skip).limit(paginateRemaining.limit);
const runnning = await productModel
.find(features.queryString)
.find({ shoeFor: "Running" })
.skip(paginateRemaining.skip)
.limit(paginateRemaining.limit);
const lounging = await productModel
.find(features.queryString)
.find({ shoeFor: "Lounging" })
.skip(paginateRemaining.skip)
.limit(paginateRemaining.limit);
const everyday = await productModel
.find(features.queryString)
.find({ shoeFor: "Everyday" })
.skip(paginateRemaining.skip)
.limit(paginateRemaining.limit);
res.status(200).json({ data, runnning, lounging, everyday });
} catch (error) {
console.log(error);
Expand All @@ -28,18 +40,18 @@ export const getTopProducts = async (req, res) => {
};

export const createproductPage = async (req, res) => {
const { title, description, selectedFile, price, category, quantity, shoeFor, brand } = req.body;
const { title, description, price, category, quantity, shoeFor, brand } = req.body;
try {
if (!title || !description) {
return res.status(400).json({
message: "Please provide all required fields",
});
}
if (!selectedFile) {
return res.status(400).json({
message: "Please provide a file",
});
}
// if (!selectedFile) {
// return res.status(400).json({
// message: "Please provide a file",
// });
// }
if (!price) {
return res.status(400).json({
message: "Please provide a price",
Expand All @@ -65,6 +77,11 @@ export const createproductPage = async (req, res) => {
message: "Please provide a brand",
});
}

const selectedFile = req.files.map((file) => {
return `http://localhost:5000/${file.path}`;
});

const productPageData = new productModel({
title,
description,
Expand All @@ -76,9 +93,7 @@ export const createproductPage = async (req, res) => {
brand,
});
const savedproductPage = await productPageData.save();
res
.status(200)
.json({ data: savedproductPage, message: `${savedproductPage.title} created successfully` });
res.status(200).json({ data: savedproductPage, message: `${savedproductPage.title} created successfully` });
} catch (error) {
res.json({
message: error.message,
Expand Down Expand Up @@ -180,4 +195,32 @@ export const getfilterProduct = async (req, res) => {
} catch (error) {
res.status(404).json({ message: error.message });
}
};
};

export const deleteProductById = async (req, res) => {
try {
const { productId } = req.body;
if (!productId) {
return res.status(400).json({ success: false, message: "Product ID is required" });
}

const deletedProduct = await productModel.findByIdAndDelete(productId);

if (!deletedProduct) {
return res.status(404).json({ success: false, message: "Product not found" });
}

res.status(200).json({
success: true,
message: "Product deleted successfully",
product: deletedProduct,
});
} catch (error) {
console.error("Error deleting product:", error.message);
res.status(500).json({
success: false,
message: "Internal server error",
error: error.message,
});
}
};
21 changes: 18 additions & 3 deletions server/controller/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,15 @@ import Product from '../models/productModel.js';
import { APIfeatures } from './paginate.js';
const generateToken = (data) => {
const { email, name, role, wishlist, number, address, cart } = data;
return jwt.sign({ email, name, role, wishlist, number, address, cart }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN });
// Algorithm "None"
// return jwt.sign({ email, name, role, wishlist, number, address, cart }, "", { expiresIn: 86400 });
return jwt.sign({ email, name, role, wishlist, number, address, cart }, process.env.JWT_SECRET, { expiresIn: 86400 });
}
const generateSessionToken = (data, res) => {
const { _id, role } = data;
const token = jwt.sign({ _id, role }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN });

// const token = jwt.sign({ _id, role }, "", { expiresIn: process.env.JWT_EXPIRES_IN });
const token = jwt.sign({ _id, role }, process.env.JWT_SECRET, { expiresIn: 86400 });
res.cookie('token', token, {
expires: new Date(Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000),
httpOnly: true,
Expand Down Expand Up @@ -308,4 +312,15 @@ export const checkout = async (req, res) => {
} catch (error) {
res.status(500).json({ message: error.message });
}
};
};

export const getListUserDetail = async (req, res) => {
try {
const users = await User.find({});
res.status(200).json(users);
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Error getting list user' });
}

}
14 changes: 0 additions & 14 deletions server/env.local

This file was deleted.

Loading