Commit 097cb3fe authored by Nawasan Wisitsingkhon's avatar Nawasan Wisitsingkhon

add wishlist from user

parent 1b360c47
import { Request, Response } from "express";
import db from "../models/prismaClient";
const WishlistController = {
/**
*
* @param {Request} req
* @param {Response} res
*/
async index(req, res) {
try {
const wishlists = await db.wishlist.findMany({
where: { user_id: Number(req.user.id) },
});
res.json({ status: 101, wishlists });
} catch (err) {
res.json({ status: 100, message: "found some error" });
}
},
/**
*
* @param {Request} req
* @param {Response} res
*/
async create(req, res) {
try {
const { id } = req.body;
if (!id) throw 200;
const check = await db.wishlist.findFirst({
where: {
AND: { user_id: Number(req.user.id), product_id: Number(id) },
},
});
if (check) throw 200;
await db.wishlist.create({
data: {
user_id: Number(req.user.id),
product_id: Number(id),
},
});
res.json({ status: 201, message: "add wishlist success" });
} catch (err) {
console.log(err);
res.json({ status: 200, message: "found some error on server" });
}
},
};
export default WishlistController;
......@@ -21,3 +21,19 @@ export const JwtAdminMiddleware = (req, res, next) => {
});
}
};
export const JwtUserMiddleware = (req, res, next) => {
try {
const { token } = req.headers;
if (!token) throw 403;
let verify = JwtCheck(token);
console.log(verify.data);
req.user = verify.data;
next();
} catch (err) {
return res.status(403).json({
status: 403,
message: "access denined",
});
}
};
import express from "express";
import WishlistController from "../controllers/WishlistController";
const UserRouter = express.Router();
UserRouter.get("/wishlist", WishlistController.index);
UserRouter.post("/wishlist", WishlistController.create);
export default UserRouter;
......@@ -2,17 +2,19 @@ import express from "express";
import WelcomeController from "../controllers/WelcomeController";
import UserController from "../controllers/UserController";
import adminRouter from "./admin";
import { JwtAdminMiddleware } from "./middleware";
import { JwtAdminMiddleware, JwtUserMiddleware } from "./middleware";
import CategoryController from "../controllers/CategoryController";
import ProductController from "../controllers/ProductController";
import UserRouter from "./user";
const route = express.Router();
route.use("/admin/", JwtAdminMiddleware, adminRouter);
route.use("/u/",JwtUserMiddleware, UserRouter);
route.get("/", WelcomeController.index);
route.get("/user", UserController.index);
route.post("/user/auth", UserController.login);
route.post("/user", UserController.create);
route.get('/category', CategoryController.index)
route.get('/product', ProductController.index)
route.get("/category", CategoryController.index);
route.get("/product", ProductController.index);
export default route;
......@@ -90,4 +90,5 @@ model order_detail {
product product @relation(fields: [product_id], references: [id])
product_price Int
product_discount Int
count Int
}
import React from "react";
import React, { useContext, useState } from "react";
import {
Card,
Box,
......@@ -14,8 +14,19 @@ import { ProductionQuantityLimits } from "@mui/icons-material";
import { AddShoppingCart } from "@mui/icons-material";
import { ShoppingCart } from "@mui/icons-material";
import { RemoveShoppingCart } from "@mui/icons-material";
import { UserContext } from "@/pages/_app";
import axios from "axios";
import { headers } from "../../next.config";
export default function ProductCard({ product, isFav }) {
export default function ProductCard({ product, isFav, favHandler }) {
const user = useContext(UserContext);
const fav = isFav
/**
*
* @param {number} id
* @param {boolean} isRemove
*/
return (
<Card
sx={{
......@@ -50,8 +61,12 @@ export default function ProductCard({ product, isFav }) {
sx={{ justifyContent: "space-between", px: 1 }}
>
<span>
<Button title={isFav ? "ถูกใจแล้ว" : "ถูกใจ"} color="error">
{isFav ? <Favorite /> : <FavoriteBorder />}
<Button
onClick={favHandler}
title={fav ? "ถูกใจแล้ว" : "ถูกใจ"}
color="error"
>
{fav ? <Favorite /> : <FavoriteBorder />}
</Button>
<Button title="เพิ่มลงตระกร้า" color="warning">
<ShoppingCart />
......@@ -65,8 +80,7 @@ export default function ProductCard({ product, isFav }) {
$
{(
Number(product.price) -
Number(product.price) *
(Number(product.discount) / 100)
Number(product.price) * (Number(product.discount) / 100)
).toLocaleString()}
</Box>
) : (
......
import axios from "axios";
import { Inter } from "next/font/google";
import Head from "next/head";
import { useEffect, useState } from "react";
import { useContext, useEffect, useState } from "react";
import ProductCard from "@/components/ProductCard";
import { useRouter } from "next/router";
import { UserContext } from "./_app";
const inter = Inter({ subsets: ["latin"] });
export default function Home() {
const user = useContext(UserContext);
const router = useRouter();
const [products, setProducts] = useState([]);
const [myWishlisth, setMywishlist] = useState([]);
const productsFilter = !!router.query?.q
? products.filter((prod) => String(prod.name).includes(router.query.q))
: products.filter((prod) => Number(prod.stock) > 0);
async function onWishlist(id, isRemove = false) {
if (isRemove) {
} else {
let response = await axios.post(
"/api/u/wishlist",
{ id },
{ headers: { token: user.value.token } }
);
console.log(response.data);
}
FetchWishlist()
}
const FetchProduct = async () => {
let response = await axios.get("/api/product");
console.log(response.data);
setProducts(response.data);
};
const FetchWishlist = async () => {
if (!user.value?.token) return;
let response = await axios.get("/api/u/wishlist", {
headers: { token: user.value.token },
});
setMywishlist(response.data.wishlists);
};
useEffect(() => {
FetchProduct();
}, []);
FetchWishlist();
console.log(myWishlisth);
console.log();
}, [user]);
return (
<>
<Head>
......@@ -32,7 +59,23 @@ export default function Home() {
<div>
<div className="mx-auto text-left grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 2xl:grid-cols-4 max-w-[1520px]">
{productsFilter.map((prod, idx) => (
<ProductCard key={idx} isFav={false} product={prod} />
<ProductCard
key={idx}
isFav={
!!myWishlisth.filter(
(wish) => wish.product_id === Number(prod.id)
).length
}
product={prod}
favHandler={() =>
onWishlist(
prod.id,
!!myWishlisth.filter(
(wish) => wish.product_id === Number(prod.id)
).length
)
}
/>
))}
</div>
</div>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment