chore: add nextjs template
This commit is contained in:
62
frontend-nextjs/app/api/images/products/[id]/route.ts
Normal file
62
frontend-nextjs/app/api/images/products/[id]/route.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { Pool } from "pg";
|
||||
|
||||
const pool = new Pool({
|
||||
host: process.env.DB_HOST || "127.0.0.1",
|
||||
port: parseInt(process.env.DB_PORT || "5432"),
|
||||
user: process.env.DB_USER || "myuser",
|
||||
password: process.env.DB_PASSWORD || "mypassword",
|
||||
database: process.env.DB_DATABASE || "mydb",
|
||||
});
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const { id } = params;
|
||||
|
||||
// Try to get image from database (stored as bytea or base64)
|
||||
const result = await pool.query(
|
||||
`SELECT image_blob, image_mime_type
|
||||
FROM products
|
||||
WHERE id = $1`,
|
||||
[id]
|
||||
);
|
||||
|
||||
if (result.rows.length === 0 || !result.rows[0].image_blob) {
|
||||
// Return a placeholder image or 404
|
||||
return NextResponse.json(
|
||||
{ error: "Image not found" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
const { image_blob, image_mime_type } = result.rows[0];
|
||||
const mimeType = image_mime_type || "image/jpeg";
|
||||
|
||||
// If stored as base64 string, decode it
|
||||
let imageBuffer: Buffer;
|
||||
if (typeof image_blob === "string") {
|
||||
// Remove data URL prefix if present
|
||||
const base64Data = image_blob.replace(/^data:image\/\w+;base64,/, "");
|
||||
imageBuffer = Buffer.from(base64Data, "base64");
|
||||
} else {
|
||||
// Already a Buffer (bytea from Postgres)
|
||||
imageBuffer = Buffer.from(image_blob);
|
||||
}
|
||||
|
||||
return new NextResponse(imageBuffer, {
|
||||
headers: {
|
||||
"Content-Type": mimeType,
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error fetching image:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch image" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
41
frontend-nextjs/app/api/products/[id]/route.ts
Normal file
41
frontend-nextjs/app/api/products/[id]/route.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { Pool } from "pg";
|
||||
|
||||
const pool = new Pool({
|
||||
host: process.env.DB_HOST || "127.0.0.1",
|
||||
port: parseInt(process.env.DB_PORT || "5432"),
|
||||
user: process.env.DB_USER || "myuser",
|
||||
password: process.env.DB_PASSWORD || "mypassword",
|
||||
database: process.env.DB_DATABASE || "mydb",
|
||||
});
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const { id } = params;
|
||||
|
||||
const result = await pool.query(
|
||||
`SELECT id, title, price_cents, slug, description
|
||||
FROM products
|
||||
WHERE id = $1`,
|
||||
[id]
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: "Product not found" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(result.rows[0]);
|
||||
} catch (error) {
|
||||
console.error("Error fetching product:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch product" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
30
frontend-nextjs/app/api/products/route.ts
Normal file
30
frontend-nextjs/app/api/products/route.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { Pool } from "pg";
|
||||
|
||||
// Database connection - uses environment variables
|
||||
const pool = new Pool({
|
||||
host: process.env.DB_HOST || "127.0.0.1",
|
||||
port: parseInt(process.env.DB_PORT || "5432"),
|
||||
user: process.env.DB_USER || "myuser",
|
||||
password: process.env.DB_PASSWORD || "mypassword",
|
||||
database: process.env.DB_DATABASE || "mydb",
|
||||
});
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const result = await pool.query(`
|
||||
SELECT id, title, price_cents, slug
|
||||
FROM products
|
||||
ORDER BY id
|
||||
LIMIT 100
|
||||
`);
|
||||
|
||||
return NextResponse.json(result.rows);
|
||||
} catch (error) {
|
||||
console.error("Error fetching products:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch products" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
15
frontend-nextjs/app/globals.css
Normal file
15
frontend-nextjs/app/globals.css
Normal file
@@ -0,0 +1,15 @@
|
||||
:root {
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
html, body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-family: system-ui, -apple-system, Segoe UI, sans-serif;
|
||||
background: #f7f7f5;
|
||||
color: #1d1d1f;
|
||||
}
|
||||
|
||||
main {
|
||||
min-height: 100vh;
|
||||
}
|
||||
9
frontend-nextjs/app/layout.tsx
Normal file
9
frontend-nextjs/app/layout.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
import "./globals.css";
|
||||
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
27
frontend-nextjs/app/listing/[product_id]/[slug]/page.tsx
Normal file
27
frontend-nextjs/app/listing/[product_id]/[slug]/page.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
import Header from "@/components/Header";
|
||||
import Footer from "@/components/Footer";
|
||||
import { fetchProduct } from "@/lib/api";
|
||||
|
||||
export default async function Page({ params }: { params: { product_id: string; slug: string } }) {
|
||||
const product = await fetchProduct(params.product_id);
|
||||
|
||||
return (
|
||||
<main>
|
||||
<Header />
|
||||
<section style={{ maxWidth: 1100, margin: "32px auto", padding: "0 24px", display: "grid", gap: 24 }}>
|
||||
<div
|
||||
style={{
|
||||
height: 360,
|
||||
borderRadius: 16,
|
||||
background: `url(${product.image_url}) center/cover no-repeat`
|
||||
}}
|
||||
/>
|
||||
<div>
|
||||
<h1 style={{ margin: 0 }}>{product.title}</h1>
|
||||
<p style={{ fontWeight: 600, fontSize: 18 }}>${(product.price_cents / 100).toFixed(2)}</p>
|
||||
</div>
|
||||
</section>
|
||||
<Footer />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
23
frontend-nextjs/app/page.tsx
Normal file
23
frontend-nextjs/app/page.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import Header from "@/components/Header";
|
||||
import Footer from "@/components/Footer";
|
||||
import ProductCard from "@/components/ProductCard";
|
||||
import { fetchProducts } from "@/lib/api";
|
||||
|
||||
export default async function Page() {
|
||||
const products = await fetchProducts();
|
||||
|
||||
return (
|
||||
<main>
|
||||
<Header />
|
||||
<section style={{ maxWidth: 1100, margin: "32px auto", padding: "0 24px" }}>
|
||||
<h1 style={{ marginBottom: 16 }}>Featured products</h1>
|
||||
<div style={{ display: "grid", gap: 16, gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))" }}>
|
||||
{products.slice(0, 8).map((product) => (
|
||||
<ProductCard key={product.id} product={product} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<Footer />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
7
frontend-nextjs/components/Footer.tsx
Normal file
7
frontend-nextjs/components/Footer.tsx
Normal file
@@ -0,0 +1,7 @@
|
||||
export default function Footer() {
|
||||
return (
|
||||
<footer style={{ padding: "24px", textAlign: "center", color: "#666" }}>
|
||||
<small>Sample footer for Next.js clone</small>
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
13
frontend-nextjs/components/Header.tsx
Normal file
13
frontend-nextjs/components/Header.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
export default function Header() {
|
||||
return (
|
||||
<header style={{ padding: "20px 24px", background: "#ffffff", borderBottom: "1px solid #e2e2e2" }}>
|
||||
<div style={{ maxWidth: 1100, margin: "0 auto", display: "flex", alignItems: "center", gap: 16 }}>
|
||||
<div style={{ fontWeight: 700 }}>Brand</div>
|
||||
<nav style={{ display: "flex", gap: 12, fontSize: 14 }}>
|
||||
<a href="/" style={{ textDecoration: "none", color: "inherit" }}>Home</a>
|
||||
<a href="/search" style={{ textDecoration: "none", color: "inherit" }}>Search</a>
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
27
frontend-nextjs/components/ProductCard.tsx
Normal file
27
frontend-nextjs/components/ProductCard.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
import { Product } from "@/lib/api";
|
||||
|
||||
export default function ProductCard({ product }: { product: Product }) {
|
||||
return (
|
||||
<article
|
||||
style={{
|
||||
border: "1px solid #e1e1e1",
|
||||
background: "#fff",
|
||||
borderRadius: 12,
|
||||
padding: 12,
|
||||
display: "grid",
|
||||
gap: 8
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
height: 160,
|
||||
borderRadius: 8,
|
||||
background: `url(${product.image_url}) center/cover no-repeat`
|
||||
}}
|
||||
/>
|
||||
<h3 style={{ margin: 0, fontSize: 14 }}>{product.title}</h3>
|
||||
<div style={{ fontWeight: 600 }}>${(product.price_cents / 100).toFixed(2)}</div>
|
||||
<a href={`/listing/${product.id}/${encodeURIComponent(product.title)}`}>View</a>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
22
frontend-nextjs/lib/api.ts
Normal file
22
frontend-nextjs/lib/api.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
export type Product = {
|
||||
id: number;
|
||||
title: string;
|
||||
price_cents: number;
|
||||
image_url: string;
|
||||
};
|
||||
|
||||
export async function fetchProducts(): Promise<Product[]> {
|
||||
const res = await fetch("/api/products", { cache: "no-store" });
|
||||
if (!res.ok) {
|
||||
throw new Error("Failed to fetch products");
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function fetchProduct(productId: string): Promise<Product> {
|
||||
const res = await fetch(`/api/products/${productId}`, { cache: "no-store" });
|
||||
if (!res.ok) {
|
||||
throw new Error("Failed to fetch product");
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
29
frontend-nextjs/lib/db.ts
Normal file
29
frontend-nextjs/lib/db.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { Pool } from "pg";
|
||||
|
||||
// Singleton database connection pool
|
||||
// Uses environment variables for configuration
|
||||
|
||||
const pool = new Pool({
|
||||
host: process.env.DB_HOST || "127.0.0.1",
|
||||
port: parseInt(process.env.DB_PORT || "5432"),
|
||||
user: process.env.DB_USER || "myuser",
|
||||
password: process.env.DB_PASSWORD || "mypassword",
|
||||
database: process.env.DB_DATABASE || "mydb",
|
||||
});
|
||||
|
||||
export default pool;
|
||||
|
||||
// Helper function for queries
|
||||
export async function query<T>(text: string, params?: unknown[]): Promise<T[]> {
|
||||
const result = await pool.query(text, params);
|
||||
return result.rows as T[];
|
||||
}
|
||||
|
||||
// Helper function for single row
|
||||
export async function queryOne<T>(
|
||||
text: string,
|
||||
params?: unknown[]
|
||||
): Promise<T | null> {
|
||||
const result = await pool.query(text, params);
|
||||
return result.rows[0] as T | null;
|
||||
}
|
||||
2
frontend-nextjs/next-env.d.ts
vendored
Normal file
2
frontend-nextjs/next-env.d.ts
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
6
frontend-nextjs/next.config.js
Normal file
6
frontend-nextjs/next.config.js
Normal file
@@ -0,0 +1,6 @@
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
reactStrictMode: true
|
||||
};
|
||||
|
||||
module.exports = nextConfig;
|
||||
22
frontend-nextjs/package.json
Normal file
22
frontend-nextjs/package.json
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "webclone-nextjs-sample",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint"
|
||||
},
|
||||
"dependencies": {
|
||||
"next": "^14.2.0",
|
||||
"react": "^18.3.0",
|
||||
"react-dom": "^18.3.0",
|
||||
"pg": "^8.11.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.5.0",
|
||||
"@types/node": "^20.16.0",
|
||||
"@types/react": "^18.3.0",
|
||||
"@types/pg": "^8.11.0"
|
||||
}
|
||||
}
|
||||
19
frontend-nextjs/tsconfig.json
Normal file
19
frontend-nextjs/tsconfig.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": false,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "preserve",
|
||||
"incremental": true
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
Reference in New Issue
Block a user