;
+
+ return (
+ <>
+
+ {showModal && (
+
+ )}
+
+ {" "}
+ {/* This is first element in the column*/}
+
+ {" "}
+ {/* This is the card with image and name + part*/}
+
+
+ {" "}
+ {/*This is for info under the picture*/}
+ {item.name}
+ Part #{item.id}
+
+
+
+ {" "}
+ {/* This is for info on the right side of the image*/}
+
${item.price.toFixed(2)}
+
Amount in stock: {item.quantity}
+
+
+
+
+
+ {" "}
+ {/* This is the card with description and categories*/}
+
{item.description}
+
+ Item Updated at : {item.updatedAt.slice(0, 10)}{" "}
+
{" "}
+
+
+ Categories:
+ {item.category}
+
+
+ {!currentUser || currentUser.role !== "admin" ? (
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ) : (
+
+
+
+
+
+
+
+
+
+ )}
+
+ >
+ );
+}
diff --git a/public/react/components/UpdateForm.jsx b/public/react/components/UpdateForm.jsx
new file mode 100644
index 0000000..2b4540c
--- /dev/null
+++ b/public/react/components/UpdateForm.jsx
@@ -0,0 +1,231 @@
+import { useContext, useEffect, useState } from "react";
+import { useNavigate, useParams } from "react-router-dom";
+import styled from "styled-components";
+import apiURL from "../api";
+import Card from "./Card";
+import { Link, useNavigate } from "react-router-dom";
+import Button from "./Button";
+import { AllStatesContext } from "./App";
+
+
+const Wrapper = styled.div`
+ display: flex;
+ flex-flow: row nowrap;
+ margin-top: 10px;
+ justify-content: space-around;
+ width: 70%;
+`;
+
+
+const FormWrapper = styled.div`
+ display: flex;
+ justify-content: left;
+ align-items: flex-start;
+ flex-flow: column nowrap;
+ margin-top: 20px;
+ gap: 5px;
+ width: 300px;
+`;
+
+const Title = styled.h3`
+ font-size: 1.5rem;
+ font-weight: bold;
+ margin-bottom: 10px;
+ width: 200px;
+`;
+
+const Preview = styled.div`
+ height: auto;
+ display: flex;
+ justify-content: center;
+ flex-flow: column nowrap;
+`;
+
+const StyledInput = styled.input`
+ width: 100%;
+ padding: 10px;
+ margin-bottom: 8px;
+ border: 1px solid #ccc;
+ border-radius: 8px;
+ font-size: 1rem;
+ transition: border 0.2s;
+ &:focus {
+ border: 1.5px solid #888;
+ outline: none;
+ background: #f8f8f8;
+ }
+`;
+
+const StyledTextarea = styled.textarea`
+ width: 100%;
+ padding: 10px;
+ margin-bottom: 8px;
+ border: 1px solid #ccc;
+ border-radius: 8px;
+ font-size: 1rem;
+ resize: vertical;
+ min-height: 60px;
+ transition: border 0.2s;
+ &:focus {
+ border: 1.5px solid #888;
+ outline: none;
+ background: #f8f8f8;
+ }
+`;
+
+const StyledLink = styled(Link)`
+ color: black;
+ text-decoration: none;
+
+ &:hover {
+ color: #333333;
+ }
+`;
+
+function UpdateByIdForm() {
+ const {handleItemUpdated} = useContext(AllStatesContext)
+ const { id } = useParams();
+ const navigate = useNavigate();
+ const [formData, setFormData] = useState({
+ name: "",
+ price: 0,
+ quantity: 0,
+ description: "",
+ category: "",
+ image: ""
+ });
+
+ useEffect(() => {
+ async function fetchItem() {
+ try {
+ const res = await fetch(`http://localhost:3000/api/items/${id}`)
+ const data = await res.json();
+ setFormData({
+ name: data?.name,
+ price: data?.price,
+ quantity: data?.quantity,
+ description: data?.description,
+ category: data?.category,
+ image: data?.image,
+ })
+ } catch (err) {
+ console.error("Error occurred: ", err)
+ }
+ }
+
+ if (id) fetchItem()
+ }, [id])
+
+ const handleChange = (e) => {
+ setFormData(prev => ({
+ ...prev,
+ [e.target.name]: e.target.value
+ }));
+ };
+
+ const handleUpdate = async (e) => {
+ e.preventDefault();
+
+ try {
+ const res = await fetch(`${apiURL}/items/${id}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(formData)
+ });
+
+ const data = await res.json();
+
+ if (res.ok) {
+ handleItemUpdated(data);
+ alert(`Item ${id} updated successfully`);
+ navigate(`/item/${id}`)
+ } else {
+ alert("Error: " + data.error);
+ }
+ } catch (error) {
+ console.error("Failed to update item", error);
+ }
+ };
+
+ return (
+
+
+
+
+ Preview:
+
+
+
+
+
+ );
+}
+
+export default UpdateByIdForm;
diff --git a/public/react/index.js b/public/react/index.js
index 9142169..17ce0ab 100644
--- a/public/react/index.js
+++ b/public/react/index.js
@@ -1,4 +1,4 @@
-import React, { StrictMode } from "react";
+import { BrowserRouter } from "react-router-dom";
import { createRoot } from "react-dom/client";
import "regenerator-runtime/runtime";
import App from "./components/App";
@@ -7,7 +7,7 @@ const container = document.getElementById("root");
const root = createRoot(container);
root.render(
-
+
-
+
);
diff --git a/public/style.css b/public/style.css
index 805db96..98d9657 100644
--- a/public/style.css
+++ b/public/style.css
@@ -1,14 +1,18 @@
* {
box-sizing: border-box;
+ margin: 0;
+ padding: 0;
+
}
-body {
- width: 88%;
- max-width: 70em;
- margin: 1em auto;
+body, html {
+ height: 100vh;
+ width: 100vw;
line-height: 1.5;
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
+ overflow-x: hidden;
+ background-color: rgb(243, 243, 243);
}
img {
diff --git a/server/items.json b/server/items.json
index f16ad93..3a13ac5 100644
--- a/server/items.json
+++ b/server/items.json
@@ -3,6 +3,7 @@
"id": 1,
"name": "Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops",
"price": 109.95,
+ "quantity": 5,
"description": "Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg"
@@ -11,6 +12,7 @@
"id": 2,
"name": "Mens Casual Premium Slim Fit T-Shirts ",
"price": 22.3,
+ "quantity": 13,
"description": "Slim-fitting style, contrast raglan long sleeve, three-button henley placket, light weight & soft fabric for breathable and comfortable wearing. And Solid stitched shirts with round neck made for durability and a great fit for casual fashion wear and diehard baseball fans. The Henley style round neckline includes a three-button placket.",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg"
@@ -19,6 +21,7 @@
"id": 3,
"name": "Mens Cotton Jacket",
"price": 55.99,
+ "quantity": 22,
"description": "great outerwear jackets for Spring/Autumn/Winter, suitable for many occasions, such as working, hiking, camping, mountain/rock climbing, cycling, traveling or other outdoors. Good gift choice for you or your family member. A warm hearted love to Father, husband or son in this thanksgiving or Christmas Day.",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/71li-ujtlUL._AC_UX679_.jpg"
@@ -27,6 +30,7 @@
"id": 4,
"name": "Mens Casual Slim Fit",
"price": 15.99,
+ "quantity": 43,
"description": "The color could be slightly different between on the screen and in practice. / Please note that body builds vary by person, therefore, detailed size information should be reviewed below on the product description.",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/71YXzeOuslL._AC_UY879_.jpg"
@@ -35,6 +39,7 @@
"id": 5,
"name": "John Hardy Women's Legends Naga Gold & Silver Dragon Station Chain Bracelet",
"price": 695,
+ "quantity": 25,
"description": "From our Legends Collection, the Naga was inspired by the mythical water dragon that protects the ocean's pearl. Wear facing inward to be bestowed with love and abundance, or outward for protection.",
"category": "jewelery",
"image": "https://fakestoreapi.com/img/71pWzhdJNwL._AC_UL640_QL65_ML3_.jpg"
@@ -43,6 +48,7 @@
"id": 6,
"name": "Solid Gold Petite Micropave ",
"price": 168,
+ "quantity": 3,
"description": "Satisfaction Guaranteed. Return or exchange any order within 30 days.Designed and sold by Hafeez Center in the United States. Satisfaction Guaranteed. Return or exchange any order within 30 days.",
"category": "jewelery",
"image": "https://fakestoreapi.com/img/61sbMiUnoGL._AC_UL640_QL65_ML3_.jpg"
@@ -51,6 +57,7 @@
"id": 7,
"name": "White Gold Plated Princess",
"price": 9.99,
+ "quantity": 7,
"description": "Classic Created Wedding Engagement Solitaire Diamond Promise Ring for Her. Gifts to spoil your love more for Engagement, Wedding, Anniversary, Valentine's Day...",
"category": "jewelery",
"image": "https://fakestoreapi.com/img/71YAIFU48IL._AC_UL640_QL65_ML3_.jpg"
@@ -59,6 +66,7 @@
"id": 8,
"name": "Pierced Owl Rose Gold Plated Stainless Steel Double",
"price": 10.99,
+ "quantity": 9,
"description": "Rose Gold Plated Double Flared Tunnel Plug Earrings. Made of 316L Stainless Steel",
"category": "jewelery",
"image": "https://fakestoreapi.com/img/51UDEzMJVpL._AC_UL640_QL65_ML3_.jpg"
@@ -67,6 +75,7 @@
"id": 9,
"name": "WD 2TB Elements Portable External Hard Drive - USB 3.0 ",
"price": 64,
+ "quantity": 6,
"description": "USB 3.0 and USB 2.0 Compatibility Fast data transfers Improve PC Performance High Capacity; Compatibility Formatted NTFS for Windows 10, Windows 8.1, Windows 7; Reformatting may be required for other operating systems; Compatibility may vary depending on user’s hardware configuration and operating system",
"category": "electronics",
"image": "https://fakestoreapi.com/img/61IBBVJvSDL._AC_SY879_.jpg"
@@ -75,6 +84,7 @@
"id": 10,
"name": "SanDisk SSD PLUS 1TB Internal SSD - SATA III 6 Gb/s",
"price": 109,
+ "quantity": 11,
"description": "Easy upgrade for faster boot up, shutdown, application load and response (As compared to 5400 RPM SATA 2.5” hard drive; Based on published specifications and internal benchmarking tests using PCMark vantage scores) Boosts burst write performance, making it ideal for typical PC workloads The perfect balance of performance and reliability Read/write speeds of up to 535MB/s/450MB/s (Based on internal testing; Performance may vary depending upon drive capacity, host device, OS and application.)",
"category": "electronics",
"image": "https://fakestoreapi.com/img/61U7T1koQqL._AC_SX679_.jpg"
@@ -83,6 +93,7 @@
"id": 11,
"name": "Silicon Power 256GB SSD 3D NAND A55 SLC Cache Performance Boost SATA III 2.5",
"price": 109,
+ "quantity": 10,
"description": "3D NAND flash are applied to deliver high transfer speeds Remarkable transfer speeds that enable faster bootup and improved overall system performance. The advanced SLC Cache Technology allows performance boost and longer lifespan 7mm slim design suitable for Ultrabooks and Ultra-slim notebooks. Supports TRIM command, Garbage Collection technology, RAID, and ECC (Error Checking & Correction) to provide the optimized performance and enhanced reliability.",
"category": "electronics",
"image": "https://fakestoreapi.com/img/71kWymZ+c+L._AC_SX679_.jpg"
@@ -91,6 +102,7 @@
"id": 12,
"name": "WD 4TB Gaming Drive Works with Playstation 4 Portable External Hard Drive",
"price": 114,
+ "quantity": 12,
"description": "Expand your PS4 gaming experience, Play anywhere Fast and easy, setup Sleek design with high capacity, 3-year manufacturer's limited warranty",
"category": "electronics",
"image": "https://fakestoreapi.com/img/61mtL65D4cL._AC_SX679_.jpg"
@@ -99,6 +111,7 @@
"id": 13,
"name": "Acer SB220Q bi 21.5 inches Full HD (1920 x 1080) IPS Ultra-Thin",
"price": 599,
+ "quantity": 16,
"description": "21. 5 inches Full HD (1920 x 1080) widescreen IPS display And Radeon free Sync technology. No compatibility for VESA Mount Refresh Rate: 75Hz - Using HDMI port Zero-frame design | ultra-thin | 4ms response time | IPS panel Aspect ratio - 16: 9. Color Supported - 16. 7 million colors. Brightness - 250 nit Tilt angle -5 degree to 15 degree. Horizontal viewing angle-178 degree. Vertical viewing angle-178 degree 75 hertz",
"category": "electronics",
"image": "https://fakestoreapi.com/img/81QpkIctqPL._AC_SX679_.jpg"
@@ -107,6 +120,7 @@
"id": 14,
"name": "Samsung 49-Inch CHG90 144Hz Curved Gaming Monitor (LC49HG90DMNXZA) – Super Ultrawide Screen QLED ",
"price": 999.99,
+ "quantity": 15,
"description": "49 INCH SUPER ULTRAWIDE 32:9 CURVED GAMING MONITOR with dual 27 inch screen side by side QUANTUM DOT (QLED) TECHNOLOGY, HDR support and factory calibration provides stunningly realistic and accurate color and contrast 144HZ HIGH REFRESH RATE and 1ms ultra fast response time work to eliminate motion blur, ghosting, and reduce input lag",
"category": "electronics",
"image": "https://fakestoreapi.com/img/81Zt42ioCgL._AC_SX679_.jpg"
@@ -115,6 +129,7 @@
"id": 15,
"name": "BIYLACLESEN Women's 3-in-1 Snowboard Jacket Winter Coats",
"price": 56.99,
+ "quantity": 22,
"description": "Note:The Jackets is US standard size, Please choose size as your usual wear Material: 100% Polyester; Detachable Liner Fabric: Warm Fleece. Detachable Functional Liner: Skin Friendly, Lightweigt and Warm.Stand Collar Liner jacket, keep you warm in cold weather. Zippered Pockets: 2 Zippered Hand Pockets, 2 Zippered Pockets on Chest (enough to keep cards or keys)and 1 Hidden Pocket Inside.Zippered Hand Pockets and Hidden Pocket keep your things secure. Humanized Design: Adjustable and Detachable Hood and Adjustable cuff to prevent the wind and water,for a comfortable fit. 3 in 1 Detachable Design provide more convenience, you can separate the coat and inner as needed, or wear it together. It is suitable for different season and help you adapt to different climates",
"category": "women's clothing",
"image": "https://fakestoreapi.com/img/51Y5NI-I5jL._AC_UX679_.jpg"
@@ -123,6 +138,7 @@
"id": 16,
"name": "Lock and Love Women's Removable Hooded Faux Leather Moto Biker Jacket",
"price": 29.95,
+ "quantity": 8,
"description": "100% POLYURETHANE(shell) 100% POLYESTER(lining) 75% POLYESTER 25% COTTON (SWEATER), Faux leather material for style and comfort / 2 pockets of front, 2-For-One Hooded denim style faux leather jacket, Button detail on waist / Detail stitching at sides, HAND WASH ONLY / DO NOT BLEACH / LINE DRY / DO NOT IRON",
"category": "women's clothing",
"image": "https://fakestoreapi.com/img/81XH0e8fefL._AC_UY879_.jpg"
@@ -131,6 +147,7 @@
"id": 17,
"name": "Rain Jacket Women Windbreaker Striped Climbing Raincoats",
"price": 39.99,
+ "quantity": 5,
"description": "Lightweight perfet for trip or casual wear---Long sleeve with hooded, adjustable drawstring waist design. Button and zipper front closure raincoat, fully stripes Lined and The Raincoat has 2 side pockets are a good size to hold all kinds of things, it covers the hips, and the hood is generous but doesn't overdo it.Attached Cotton Lined Hood with Adjustable Drawstrings give it a real styled look.",
"category": "women's clothing",
"image": "https://fakestoreapi.com/img/71HblAHs5xL._AC_UY879_-2.jpg"
@@ -139,6 +156,7 @@
"id": 18,
"name": "MBJ Women's Solid Short Sleeve Boat Neck V ",
"price": 9.85,
+ "quantity": 31,
"description": "95% RAYON 5% SPANDEX, Made in USA or Imported, Do Not Bleach, Lightweight fabric with great stretch for comfort, Ribbed on sleeves and neckline / Double stitching on bottom hem",
"category": "women's clothing",
"image": "https://fakestoreapi.com/img/71z3kpMAYsL._AC_UY879_.jpg"
@@ -147,6 +165,7 @@
"id": 19,
"name": "Opna Women's Short Sleeve Moisture",
"price": 7.95,
+ "quantity": 27,
"description": "100% Polyester, Machine wash, 100% cationic polyester interlock, Machine Wash & Pre Shrunk for a Great Fit, Lightweight, roomy and highly breathable with moisture wicking fabric which helps to keep moisture away, Soft Lightweight Fabric with comfortable V-neck collar and a slimmer fit, delivers a sleek, more feminine silhouette and Added Comfort",
"category": "women's clothing",
"image": "https://fakestoreapi.com/img/51eg55uWmdL._AC_UX679_.jpg"
@@ -155,6 +174,7 @@
"id": 20,
"name": "DANVOUY Womens T Shirt Casual Cotton Short",
"price": 12.99,
+ "quantity": 13,
"description": "95%Cotton,5%Spandex, Features: Casual, Short Sleeve, Letter Print,V-Neck,Fashion Tees, The fabric is soft and has some stretch., Occasion: Casual/Office/Beach/School/Home/Street. Season: Spring,Summer,Autumn,Winter.",
"category": "women's clothing",
"image": "https://fakestoreapi.com/img/61pHAEJ4NML._AC_UX679_.jpg"
diff --git a/server/models/Item.js b/server/models/Item.js
index 764313c..f2ccc69 100644
--- a/server/models/Item.js
+++ b/server/models/Item.js
@@ -5,10 +5,51 @@ class Item extends Model {}
Item.init(
{
- // Define your columns here
+ name: {
+ type: DataTypes.STRING,
+ allowNull: false,
+ validate: {
+ notEmpty: { msg: "Name cannot be empty" },
+ },
+ },
+ price: {
+ type: DataTypes.FLOAT,
+ allowNull: false,
+ validate: {
+ isFloat: { msg: "Price must be a valid number" },
+ min: { args: [0], msg: "Price must be at least 0" },
+ },
+ },
+ quantity: {
+ type: DataTypes.INTEGER,
+ allowNull: false,
+ validate: {
+ isInt: { msg: "Quantity must be an integer" },
+ min: { args: [0], msg: "Quantity cannot be negative" },
+ },
+ },
+ description: {
+ type: DataTypes.TEXT,
+ },
+ category: {
+ type: DataTypes.STRING,
+ allowNull: false,
+ validate: {
+ notEmpty: { msg: "Category cannot be empty" },
+ },
+ },
+ image: {
+ type: DataTypes.STRING,
+ allowNull: false,
+ validate: {
+ notEmpty: { msg: "Image URL is required" },
+ isUrl: { msg: "Image must be a valid URL" },
+ },
+ },
},
{
sequelize,
+ modelName: "Item",
}
);
diff --git a/server/models/Order.js b/server/models/Order.js
new file mode 100644
index 0000000..271620d
--- /dev/null
+++ b/server/models/Order.js
@@ -0,0 +1,28 @@
+const { Model, DataTypes } = require("sequelize");
+const sequelize = require("../db");
+const User = require("./User");
+
+class Order extends Model {}
+
+Order.init(
+ {
+ status: {
+ type: DataTypes.ENUM("pending", "completed"),
+ defaultValue: "pending",
+ allowNull: false,
+ validate: {
+ isIn: {
+ args: [["pending", "completed"]],
+ msg: "Status must be either 'pending' or 'completed'",
+ },
+ },
+ },
+ },
+ {
+ sequelize,
+ modelName: "order",
+ }
+);
+
+
+module.exports = Order;
diff --git a/server/models/User.js b/server/models/User.js
new file mode 100644
index 0000000..c336347
--- /dev/null
+++ b/server/models/User.js
@@ -0,0 +1,39 @@
+const { Model, DataTypes } = require("sequelize");
+const sequelize = require("../db");
+
+class User extends Model {}
+
+User.init({
+ username: {
+ type: DataTypes.STRING,
+ allowNull: false,
+ unique: {
+ msg: 'Username already exists'
+ },
+ validate: {
+ notEmpty: { msg: 'Username is required' },
+ len: {
+ args: [3, 20],
+ msg: 'Username must be between 3 and 20 characters'
+ }
+ }
+ },
+ password: {
+ type: DataTypes.STRING,
+ allowNull: false,
+ validate: {
+ notEmpty: { msg: 'Password is required' },
+ len: {
+ args: [6, 100],
+ msg: 'Password must be at least 6 characters'
+ }
+ }
+ },
+ role: {
+ type: DataTypes.ENUM('admin', 'customer'),
+ defaultValue: 'customer',
+ }
+ }, { sequelize, modelName: "user" });
+
+
+module.exports = User;
diff --git a/server/models/index.js b/server/models/index.js
index 7e8b7aa..bb3985f 100644
--- a/server/models/index.js
+++ b/server/models/index.js
@@ -1,5 +1,8 @@
const Item = require("./Item");
-
+const User = require('./User');
+const Order = require('./Order');
module.exports = {
Item,
+ User,
+ Order,
};
diff --git a/server/routes/index.js b/server/routes/index.js
index fb9a406..62d6ebc 100644
--- a/server/routes/index.js
+++ b/server/routes/index.js
@@ -3,5 +3,7 @@ const router = express.Router();
// different model routers
router.use("/items", require("./items"));
+router.use("/users", require("./users"));
+router.use("/orders", require("./orders"));
module.exports = router;
diff --git a/server/routes/items.js b/server/routes/items.js
index 9ec053a..9e4d00f 100644
--- a/server/routes/items.js
+++ b/server/routes/items.js
@@ -5,5 +5,75 @@ const router = express.Router();
router.use(express.json());
// Define your routes here
+// GET all items
+router.get("/", async (req, res) => {
+ const items = await Item.findAll();
+ res.json(items);
+ });
+
+ // GET one item
+ router.get("/:id", async (req, res) => {
+ const item = await Item.findByPk(req.params.id);
+ if (!item) return res.status(404).json({ error: "Item not found" });
+ res.json(item);
+ });
+
+ // UPDATE item
+ router.put("/:id", async (req, res) => {
+ const item = await Item.findByPk(req.params.id);
+ if (!item) return res.status(404).json({ error: "Item not found" });
+
+ if (!item.name || !item.category || !item.image) {
+ return res.status(400).json({ error: "Missing required fields" });
+ }
+
+ if (item.price <= 0) {
+ return res.status(400).json({ error: "Price cannot be $0" });
+ }
+
+ if (item.quantity < 0) {
+ return res.status(400).json({ error: "Quantity cannot be negative" });
+ }
+
+ try {
+ await item.update(req.body);
+ res.json(item);
+ } catch (err) {
+ res.status(400).json({ error: err.message });
+ }
+ });
+
+ // DELETE item
+ router.delete("/:id", async (req, res) => {
+ const item = await Item.findByPk(req.params.id);
+ if (!item) return res.status(404).json({ error: "Item not found" });
+
+ await item.destroy();
+ res.json({ message: "Item deleted" });
+ });
+
+// CREATE new item with basic validation
+router.post("/", async (req, res) => {
+ const { name, price, quantity, category, image } = req.body;
+
+ if (!name || !category || !image) {
+ return res.status(400).json({ error: "Missing required fields" });
+ }
+
+ if (price <= 0) {
+ return res.status(400).json({ error: "Price cannot be $0" });
+ }
+
+ if (quantity < 0) {
+ return res.status(400).json({ error: "Quantity cannot be negative" });
+ }
+
+ try {
+ const newItem = await Item.create(req.body);
+ res.status(201).json(newItem);
+ } catch (err) {
+ res.status(400).json({ error: err.message });
+ }
+});
module.exports = router;
diff --git a/server/routes/orders.js b/server/routes/orders.js
new file mode 100644
index 0000000..2bac60f
--- /dev/null
+++ b/server/routes/orders.js
@@ -0,0 +1,36 @@
+// routes/orders.js
+const express = require("express");
+const router = express.Router();
+const { Order, User } = require("../models");
+
+// GET all orders
+router.get("/", async (req, res) => {
+ const orders = await Order.findAll({ include: User });
+ res.json(orders);
+});
+
+// POST new order
+router.post("/", async (req, res) => {
+ const { userId, status } = req.body;
+
+ // Check if userId was provided
+ if (!userId) {
+ return res.status(400).json({ error: "userId is required" });
+ }
+
+ // Check if user exists
+ const user = await User.findByPk(userId);
+ if (!user) {
+ return res.status(404).json({ error: "User not found" });
+ }
+
+ // Create the order
+ try {
+ const order = await Order.create({ userId, status });
+ res.status(201).json(order);
+ } catch (err) {
+ res.status(400).json({ error: err.message });
+ }
+});
+
+module.exports = router;
diff --git a/server/routes/users.js b/server/routes/users.js
new file mode 100644
index 0000000..ae6df38
--- /dev/null
+++ b/server/routes/users.js
@@ -0,0 +1,36 @@
+// routes/users.js
+const express = require('express');
+const router = express.Router();
+const { User } = require('../models');
+
+// GET all users
+router.get('/', async (req, res) => {
+ const users = await User.findAll();
+ res.json(users);
+});
+
+// GET a user by ID
+router.post('/login', async (req, res) => {
+ const {username, password} = req.body;
+ const user = await User.findOne({where: {username}})
+ if (!user) {
+ return res.status(404).json({error: "User doesn't exist"})
+ }
+ if (user.password !== password) {
+ return res.status(401).json({error: "Wrong password"})
+ }
+ res.json(user);
+});
+
+// POST a new user
+router.post('/', async (req, res) => {
+ const {username, password, role} = req.body;
+ try {
+ const user = await User.create({username, password, role});
+ res.status(201).json(user);
+ } catch (err) {
+ res.status(400).json({ error: err.message });
+ }
+});
+
+module.exports = router;
diff --git a/server/seed.js b/server/seed.js
index 72e3236..dc6d6ec 100644
--- a/server/seed.js
+++ b/server/seed.js
@@ -3,7 +3,8 @@ const { Item } = require("./models");
const items = require("./items.json");
async function seed() {
- await sequelize.sync({ force: true });
+ //await sequelize.sync({ force: true });
+ await Item.sync();
await Item.bulkCreate(items);
console.log("Database populated");
}