feat: init drizzle implementation for backend (express) and frontend (vite-react)
This commit is contained in:
parent
fc3a21263a
commit
aca6a4da98
17 changed files with 1608 additions and 35 deletions
2
apps/express-template/.env.example
Normal file
2
apps/express-template/.env.example
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
# Drizzle ORM configuration for Supabase PostgreSQL database
|
||||
DATABASE_URL=
|
||||
78
apps/express-template/src/routes/users.ts
Normal file
78
apps/express-template/src/routes/users.ts
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
import { Router } from "express";
|
||||
import { getUsers, createUser } from "@repo/db/index.ts";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
const router = Router();
|
||||
|
||||
// GET /api/users - Get all users
|
||||
router.get("/", async (req, res) => {
|
||||
try {
|
||||
const users = await getUsers();
|
||||
res.json(users);
|
||||
} catch (error: any) {
|
||||
console.error("Error fetching users:", error);
|
||||
res.status(500).json({
|
||||
error: "Failed to fetch users",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/users - Create new user
|
||||
router.post("/", async (req, res) => {
|
||||
try {
|
||||
const { name, email, password, role, isActive } = req.body;
|
||||
|
||||
// Validation
|
||||
if (!name || !email || !password) {
|
||||
return res.status(400).json({
|
||||
error: "Missing required fields: name, email, and password are required",
|
||||
});
|
||||
}
|
||||
|
||||
// Email format validation
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
return res.status(400).json({ error: "Invalid email format" });
|
||||
}
|
||||
|
||||
// Password length validation
|
||||
if (password.length < 6) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: "Password must be at least 6 characters long" });
|
||||
}
|
||||
|
||||
// Role validation (based on schema enum)
|
||||
const validRoles = ["admin", "user"];
|
||||
if (role && !validRoles.includes(role)) {
|
||||
return res.status(400).json({
|
||||
error: "Invalid role. Must be 'admin' or 'user'",
|
||||
});
|
||||
}
|
||||
const userData = {
|
||||
id: randomUUID(),
|
||||
name: name.trim(),
|
||||
email: email.toLowerCase().trim(),
|
||||
role: role || "user", // Default role
|
||||
};
|
||||
|
||||
const newUser = await createUser(userData);
|
||||
|
||||
res.status(201).json(newUser);
|
||||
} catch (error: any) {
|
||||
console.error("Error creating user:", error);
|
||||
|
||||
// Handle unique constraint violation (duplicate email)
|
||||
if (error.message?.includes("duplicate") || error.code === "23505") {
|
||||
return res.status(409).json({ error: "Email already exists" });
|
||||
}
|
||||
|
||||
res.status(500).json({
|
||||
error: "Failed to create user",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
|
@ -2,21 +2,25 @@ import { json, urlencoded } from "body-parser";
|
|||
import express, { type Express } from "express";
|
||||
import morgan from "morgan";
|
||||
import cors from "cors";
|
||||
import productRoutes from "./routes/products";
|
||||
import userRoutes from "./routes/users";
|
||||
|
||||
export const createServer = (): Express => {
|
||||
const app = express();
|
||||
app
|
||||
.disable("x-powered-by")
|
||||
.use(morgan("dev"))
|
||||
.use(urlencoded({ extended: true }))
|
||||
.use(json())
|
||||
.use(cors())
|
||||
.get("/message/:name", (req, res) => {
|
||||
return res.json({ message: `hello ${req.params.name}` });
|
||||
})
|
||||
.get("/status", (_, res) => {
|
||||
return res.json({ ok: true });
|
||||
});
|
||||
const app = express();
|
||||
app.disable("x-powered-by")
|
||||
.use(morgan("dev"))
|
||||
.use(urlencoded({ extended: true }))
|
||||
.use(json())
|
||||
.use(cors())
|
||||
|
||||
return app;
|
||||
.get("/message/:name", (req, res) => {
|
||||
return res.json({ message: `hello ${req.params.name}` });
|
||||
})
|
||||
.get("/status", (_, res) => {
|
||||
return res.json({ ok: true });
|
||||
})
|
||||
|
||||
.use("/api/products", productRoutes)
|
||||
.use("/api/users", userRoutes);
|
||||
return app;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
{
|
||||
"extends": "@repo/typescript-config/base.json",
|
||||
"compilerOptions": {
|
||||
"lib": ["ES2015"],
|
||||
"outDir": "./dist"
|
||||
},
|
||||
"exclude": ["node_modules"],
|
||||
"include": ["."]
|
||||
"extends": "@repo/typescript-config/base.json",
|
||||
"compilerOptions": {
|
||||
"lib": ["ES2015"],
|
||||
"outDir": "./dist"
|
||||
},
|
||||
"exclude": ["node_modules"],
|
||||
"include": ["."]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1 +1,3 @@
|
|||
VITE_CLERK_PUBLISHABLE_KEY=
|
||||
VITE_CLERK_PUBLISHABLE_KEY=
|
||||
|
||||
VITE_API_BASE_URL=http://localhost:5001
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@ import "@repo/ui/styles/styles.css";
|
|||
import "@repo/ui/styles/global.css";
|
||||
import { CounterButton } from "@repo/ui/counter-button";
|
||||
import { Link } from "@repo/ui/link";
|
||||
import ProductForm from "./ProductForm";
|
||||
import ProductIndex from "./ProductIndex";
|
||||
|
||||
import { Button } from "@repo/ui/components/button";
|
||||
import {
|
||||
|
|
@ -69,6 +71,9 @@ function App() {
|
|||
Vite
|
||||
</Link>
|
||||
</p>
|
||||
|
||||
<ProductForm />
|
||||
<ProductIndex />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
76
apps/vite-template/src/app/productForm.tsx
Normal file
76
apps/vite-template/src/app/productForm.tsx
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import React, { useState } from "react";
|
||||
import {
|
||||
ProductCreate,
|
||||
ProductCreateData,
|
||||
} from "@repo/ui/components/products/create";
|
||||
|
||||
interface ProductFormProps {
|
||||
onSuccess?: (product: ProductCreateData) => void;
|
||||
onCancel?: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const ProductForm: React.FC<ProductFormProps> = ({
|
||||
onSuccess,
|
||||
onCancel,
|
||||
className,
|
||||
}) => {
|
||||
const [isVisible, setIsVisible] = useState(true);
|
||||
const apiBaseUrl =
|
||||
import.meta.env.VITE_API_BASE_URL || "http://localhost:5001";
|
||||
|
||||
const handleProductCreated = (product: ProductCreateData) => {
|
||||
console.log("Product created successfully:", product);
|
||||
|
||||
// Call the success callback if provided
|
||||
if (onSuccess) {
|
||||
onSuccess(product);
|
||||
}
|
||||
|
||||
// Optionally hide the form after successful creation
|
||||
// setIsVisible(false);
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
console.log("Product creation cancelled");
|
||||
|
||||
if (onCancel) {
|
||||
onCancel();
|
||||
} else {
|
||||
// Default behavior: hide the form
|
||||
setIsVisible(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleForm = () => {
|
||||
setIsVisible(!isVisible);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
{/* Toggle Button */}
|
||||
<div className="mb-4">
|
||||
<button
|
||||
onClick={handleToggleForm}
|
||||
className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors"
|
||||
>
|
||||
{isVisible ? "Hide Form" : "Add New Product"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Product Create Form */}
|
||||
{isVisible && (
|
||||
<div className="max-w-2xl">
|
||||
<ProductCreate
|
||||
onSuccess={handleProductCreated}
|
||||
onCancel={handleCancel}
|
||||
apiEndpoint={`${apiBaseUrl}/api/products`}
|
||||
className="shadow-lg"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProductForm;
|
||||
153
apps/vite-template/src/app/productIndex.tsx
Normal file
153
apps/vite-template/src/app/productIndex.tsx
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
import React, { useEffect, useState, useCallback } from "react";
|
||||
import { ProductGrid } from "@repo/ui/components/products/index";
|
||||
import { PaginatedResponse } from "@repo/ui/components/template/table-show";
|
||||
|
||||
interface Product {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
price: number;
|
||||
imageUrl?: string;
|
||||
isPublished?: boolean;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || "http://localhost:5001";
|
||||
|
||||
const fetchProducts = async (
|
||||
page: number = 1,
|
||||
limit: number = 10
|
||||
): Promise<PaginatedResponse<Product>> => {
|
||||
const response = await fetch(
|
||||
`${apiBaseUrl}/api/products?page=${page}&limit=${limit}`
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch products");
|
||||
}
|
||||
return response.json();
|
||||
};
|
||||
|
||||
const ProductIndex: React.FC = () => {
|
||||
const [paginatedProducts, setPaginatedProducts] = useState<
|
||||
PaginatedResponse<Product>
|
||||
>({
|
||||
data: [],
|
||||
pagination: {
|
||||
page: 1,
|
||||
limit: 10,
|
||||
totalCount: 0,
|
||||
totalPages: 0,
|
||||
hasNextPage: false,
|
||||
hasPreviousPage: false,
|
||||
},
|
||||
});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const loadProducts = useCallback(async (page: number = 1) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const result = await fetchProducts(page);
|
||||
setPaginatedProducts(result);
|
||||
setError(null);
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadProducts(1);
|
||||
}, [loadProducts]);
|
||||
|
||||
const handlePageChange = (page: number) => {
|
||||
loadProducts(page);
|
||||
};
|
||||
|
||||
const handleEdit = (product: Product) => {
|
||||
// TODO: Implement edit functionality for Vite app
|
||||
console.log("Edit product:", product);
|
||||
};
|
||||
|
||||
const handleDelete = async (productId: string) => {
|
||||
if (!confirm("Are you sure you want to delete this product?")) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${apiBaseUrl}/api/products/${productId}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to delete product");
|
||||
}
|
||||
|
||||
// Refresh current page
|
||||
loadProducts(paginatedProducts.pagination.page);
|
||||
} catch (err: any) {
|
||||
console.error("Delete error:", err.message);
|
||||
alert("Failed to delete product: " + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading && paginatedProducts.data.length === 0) {
|
||||
return (
|
||||
<div className="flex justify-center items-center min-h-64">
|
||||
<div className="text-lg text-gray-600">Loading products...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex flex-col justify-center items-center min-h-64 space-y-4">
|
||||
<div className="text-red-600 bg-red-50 p-4 rounded-md max-w-md text-center">
|
||||
<h3 className="font-semibold mb-2">
|
||||
Error Loading Products
|
||||
</h3>
|
||||
<p>{error}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => loadProducts(1)}
|
||||
className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-6 space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<h2 className="text-3xl font-bold">Products</h2>
|
||||
<p className="text-gray-600 mt-1">
|
||||
{paginatedProducts.pagination.totalCount} product
|
||||
{paginatedProducts.pagination.totalCount !== 1
|
||||
? "s"
|
||||
: ""}{" "}
|
||||
found
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ProductGrid
|
||||
paginatedProducts={paginatedProducts}
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDelete}
|
||||
onPageChange={handlePageChange}
|
||||
loading={loading}
|
||||
className="mt-6"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProductIndex;
|
||||
|
|
@ -1,10 +1,10 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"skipLibCheck": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"allowSyntheticDefaultImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"skipLibCheck": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"allowSyntheticDefaultImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue