feat: init next-template integration with drizzle

This commit is contained in:
afiqzudinhadi 2025-07-08 21:17:52 +08:00
parent 9e418621e0
commit 7d3ce5c604
6 changed files with 454 additions and 2 deletions

View file

@ -1,2 +1,5 @@
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=
CLERK_SECRET_KEY=
CLERK_SECRET_KEY=
# Drizzle ORM configuration for Supabase PostgreSQL database
DATABASE_URL=

View file

@ -0,0 +1,162 @@
import { NextRequest, NextResponse } from "next/server";
import { getProducts, createProduct } from "@repo/db/index";
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const page = parseInt(searchParams.get("page") || "1");
const limit = parseInt(searchParams.get("limit") || "10");
// Validate pagination parameters
if (page < 1 || limit < 1 || limit > 100) {
return NextResponse.json(
{
error: "Invalid pagination parameters. Page must be >= 1, limit must be 1-100",
},
{ status: 400 }
);
}
const result = await getProducts(page, limit);
return NextResponse.json(result);
} catch (error: any) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Failed to fetch products", message: error.message },
{ status: 500 }
);
}
}
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { name, description, price, imageUrl, isPublished } = body;
// Enhanced validation
if (!name || typeof name !== "string" || !name.trim()) {
return NextResponse.json(
{
error: "Product name is required and must be a non-empty string",
},
{ status: 400 }
);
}
if (price === undefined || price === null || isNaN(Number(price))) {
return NextResponse.json(
{ error: "Price is required and must be a valid number" },
{ status: 400 }
);
}
const priceValue = Number(price);
if (priceValue < 0) {
return NextResponse.json(
{ error: "Price must be non-negative" },
{ status: 400 }
);
}
// Validate optional fields
if (description && typeof description !== "string") {
return NextResponse.json(
{ error: "Description must be a string" },
{ status: 400 }
);
}
if (imageUrl && typeof imageUrl !== "string") {
return NextResponse.json(
{ error: "Image URL must be a string" },
{ status: 400 }
);
}
// Validate URL format if provided
if (imageUrl && imageUrl.trim()) {
try {
new URL(imageUrl.trim());
} catch {
return NextResponse.json(
{ error: "Image URL must be a valid URL" },
{ status: 400 }
);
}
}
// Prepare product data
const productData = {
name: name.trim(),
description: description?.trim() || null,
price: priceValue,
imageUrl: imageUrl?.trim() || null,
isPublished: Boolean(isPublished),
};
// Create product in database
const newProduct = await createProduct(productData);
// Return success response with created product
return NextResponse.json(
{
success: true,
message: "Product created successfully",
data: newProduct,
},
{ status: 201 }
);
} catch (error: any) {
console.error("API Error:", error);
// Handle specific database errors
if (error.message?.includes("duplicate") || error.code === "23505") {
return NextResponse.json(
{
success: false,
error: "Product already exists",
message: "A product with this name already exists",
},
{ status: 409 }
);
}
// Handle database connection errors
if (error.code === "ENOTFOUND" || error.code === "ECONNREFUSED") {
return NextResponse.json(
{
success: false,
error: "Database connection failed",
message: "Unable to connect to database",
},
{ status: 503 }
);
}
// Handle validation errors from database
if (error.code === "23502") {
// NOT NULL violation
return NextResponse.json(
{
success: false,
error: "Missing required field",
message: "A required field is missing",
},
{ status: 400 }
);
}
// Generic error response
return NextResponse.json(
{
success: false,
error: "Failed to create product",
message: error.message || "An unexpected error occurred",
...(process.env.NODE_ENV === "development" && {
stack: error.stack,
}),
},
{ status: 500 }
);
}
}

View file

@ -0,0 +1,67 @@
"use client";
import React, { useState } from "react";
import {
ProductCreate,
ProductCreateData,
} from "@repo/ui/components/products/create";
import { Button } from "@repo/ui/components/button";
interface CreateFormProps {
onProductCreated?: () => void;
className?: string;
}
const CreateForm: React.FC<CreateFormProps> = ({
onProductCreated,
className,
}) => {
const [showForm, setShowForm] = useState(false);
const handleProductCreated = (product: ProductCreateData) => {
console.log("Product created successfully:", product);
// Hide the form after successful creation
setShowForm(false);
// Trigger parent to refresh products list
if (onProductCreated) {
onProductCreated();
}
};
const handleCancel = () => {
setShowForm(false);
};
const toggleForm = () => {
setShowForm(!showForm);
};
return (
<div className={className}>
{/* Toggle Button */}
<div className="mb-6">
<Button
onClick={toggleForm}
variant={showForm ? "outline" : "default"}
>
{showForm ? "Cancel" : "Add New Product"}
</Button>
</div>
{/* Create Form */}
{showForm && (
<div className="mb-6 max-w-md">
<ProductCreate
onSuccess={handleProductCreated}
onCancel={handleCancel}
apiEndpoint="/api/products"
className="bg-white border rounded-lg shadow-sm"
/>
</div>
)}
</div>
);
};
export default CreateForm;

View file

@ -0,0 +1,166 @@
"use client";
import React, { useState, useCallback } from "react";
import { ProductGrid } from "@repo/ui/components/products/index";
import { PaginatedResponse } from "@repo/ui/components/template/table-show";
import { Button } from "@repo/ui/components/button";
import CreateForm from "./create-form";
interface Product {
id: string;
name: string;
description: string;
price: number;
imageUrl?: string;
isPublished?: boolean;
created_at?: string;
updated_at?: string;
}
interface PageClientProps {
initialPaginatedProducts: PaginatedResponse<Product>;
initialError: string | null;
}
const fetchProducts = async (
page: number = 1,
limit: number = 10
): Promise<PaginatedResponse<Product>> => {
const response = await fetch(`/api/products?page=${page}&limit=${limit}`);
if (!response.ok) {
throw new Error("Failed to fetch products");
}
return response.json();
};
const PageClient: React.FC<PageClientProps> = ({
initialPaginatedProducts,
initialError,
}) => {
const [paginatedProducts, setPaginatedProducts] = useState<
PaginatedResponse<Product>
>(initialPaginatedProducts);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(initialError);
const loadProducts = useCallback(async (page: number = 1) => {
try {
setLoading(true);
setError(null);
const result = await fetchProducts(page);
setPaginatedProducts(result);
} catch (err: any) {
console.error("Failed to load products:", err);
setError(err.message || "Failed to load products");
} finally {
setLoading(false);
}
}, []);
const handlePageChange = (page: number) => {
loadProducts(page);
};
const handleEdit = (product: Product) => {
// TODO: Implement edit functionality
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(`/api/products/${productId}`, {
method: "DELETE",
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error || "Failed to delete product");
}
// Refresh current page after deletion
await loadProducts(paginatedProducts.pagination.page);
} catch (err: any) {
console.error("Delete error:", err);
alert(`Failed to delete product: ${err.message}`);
}
};
const handleProductCreated = useCallback(() => {
// Refresh products list and go to first page to see the new product
loadProducts(1);
}, [loadProducts]);
// Show loading state when no data and loading
if (loading && paginatedProducts.data.length === 0 && !error) {
return (
<div className="flex justify-center items-center min-h-64">
<div className="text-lg text-gray-600">Loading products...</div>
</div>
);
}
// Show error state
if (error && paginatedProducts.data.length === 0) {
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)} variant="outline">
Try Again
</Button>
</div>
);
}
return (
<div className="container mx-auto p-6 space-y-6">
{/* Header Section */}
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold">Products</h1>
<p className="text-gray-600 mt-1">
{paginatedProducts.pagination.totalCount} product
{paginatedProducts.pagination.totalCount !== 1
? "s"
: ""}{" "}
found
</p>
</div>
</div>
{/* Create Product Form */}
<CreateForm
onProductCreated={handleProductCreated}
className="mb-6"
/>
{/* Error Banner (when products exist but there's an error) */}
{error && paginatedProducts.data.length > 0 && (
<div className="bg-red-50 border border-red-200 text-red-600 px-4 py-3 rounded-md">
<p>
<strong>Warning:</strong> {error}
</p>
</div>
)}
{/* Products Grid */}
<ProductGrid
paginatedProducts={paginatedProducts}
onEdit={handleEdit}
onDelete={handleDelete}
onPageChange={handlePageChange}
loading={loading}
className="mt-6"
/>
</div>
);
};
export default PageClient;

View file

@ -0,0 +1,53 @@
import React from "react";
import { getProducts } from "@repo/db/index";
import PageClient from "./page-client";
import { Product } from "@repo/ui/components/products";
import { PaginatedResponse } from "@repo/ui/components/template/table-show";
export default async function ProductPage() {
// Fetch initial data on the server (first page)
let initialPaginatedProducts: PaginatedResponse<Product> = {
data: [],
pagination: {
page: 1,
limit: 10,
totalCount: 0,
totalPages: 0,
hasNextPage: false,
hasPreviousPage: false,
},
};
let initialError = null;
try {
const result = await getProducts(1, 10); // Get first page with 10 items
initialPaginatedProducts = {
data: result.data.map((product: any) => ({
...product,
id: String(product.id), // Convert to string for consistency
description: product.description ?? "",
imageUrl: product.imageUrl ?? undefined,
isPublished: product.isPublished ?? false,
created_at: product.createdAt
? product.createdAt.toISOString()
: undefined,
updated_at: product.updatedAt
? product.updatedAt.toISOString()
: undefined,
})),
pagination: result.pagination,
};
} catch (error: any) {
console.error("Failed to fetch initial products:", error);
initialError = error.message;
}
return (
<div className="container">
<PageClient
initialPaginatedProducts={initialPaginatedProducts}
initialError={initialError}
/>
</div>
);
}

View file

@ -10,7 +10,8 @@
],
"paths": {
"~/*": ["./src/*"],
"@repo/ui/*": ["../../packages/ui/src/*"]
"@repo/ui/*": ["../../packages/ui/src/*"],
"@repo/db/*": ["../../packages/db/src/*"]
}
},
"include": ["src", "next.config.ts", "next-env.d.ts", ".next/types/**/*.ts"]