cg / hackerproducts

63 files · 5,740 lines · 159.1 KB — Next.js 15, React 19, TypeScript, PostgreSQL, Object Storage, plain CSS.

Quick jump: page.tsx / page.tsx / globals.css / schema.sql / package.json

root / src / db / index.ts

src/db/index.ts · 161 lines · 5.2 KB← back to folder
1import { Pool, type QueryResult, type QueryResultRow } from "pg";
2import fs from "node:fs";
3import path from "node:path";
4
5declare global {
6 // eslint-disable-next-line no-var
7 var __hpPool: Pool | undefined;
8 // eslint-disable-next-line no-var
9 var __hpSchemaReady: Promise<void> | undefined;
10}
11
12export function isDatabaseConfigured(): boolean {
13 return Boolean(process.env.DATABASE_URL && process.env.DATABASE_URL.trim().length > 0);
14}
15
16function createPool(): Pool {
17 const connectionString = process.env.DATABASE_URL;
18 if (!connectionString) {
19 throw new Error("DATABASE_URL is not configured.");
20 }
21
22 const requiresSsl =
23 connectionString.includes("sslmode=require") ||
24 connectionString.includes("neon.tech") ||
25 connectionString.includes("supabase.co");
26
27 return new Pool({
28 connectionString,
29 max: 5,
30 idleTimeoutMillis: 15000,
31 connectionTimeoutMillis: 10000,
32 ssl: requiresSsl ? { rejectUnauthorized: false } : undefined,
33 });
34}
35
36export function getPool(): Pool {
37 if (!globalThis.__hpPool) {
38 globalThis.__hpPool = createPool();
39 }
40 return globalThis.__hpPool;
41}
42
43const SCHEMA_SQL = `
44CREATE TABLE IF NOT EXISTS users (
45 id TEXT PRIMARY KEY,
46 username TEXT NOT NULL UNIQUE,
47 email TEXT UNIQUE,
48 name TEXT,
49 avatar_url TEXT,
50 bio TEXT DEFAULT '',
51 website_url TEXT DEFAULT '',
52 provider TEXT NOT NULL,
53 provider_account_id TEXT NOT NULL,
54 password_hash TEXT,
55 is_admin BOOLEAN NOT NULL DEFAULT FALSE,
56 created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
57 updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
58 CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9][a-z0-9_-]{0,38}$'),
59 CONSTRAINT users_provider_unique UNIQUE (provider, provider_account_id)
60);
61
62CREATE TABLE IF NOT EXISTS sessions (
63 token_hash TEXT PRIMARY KEY,
64 user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
65 expires_at TIMESTAMPTZ NOT NULL,
66 created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
67);
68
69CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id);
70CREATE INDEX IF NOT EXISTS idx_sessions_expires_at ON sessions(expires_at);
71
72CREATE TABLE IF NOT EXISTS products (
73 id TEXT PRIMARY KEY,
74 owner_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
75 name TEXT NOT NULL,
76 slug TEXT NOT NULL UNIQUE,
77 website_url TEXT NOT NULL,
78 description TEXT NOT NULL,
79 readme_md TEXT NOT NULL,
80 icon_url TEXT,
81 screenshot_url TEXT,
82 status TEXT NOT NULL DEFAULT 'published',
83 published_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
84 created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
85 updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
86 CONSTRAINT products_description_len CHECK (char_length(description) <= 160),
87 CONSTRAINT products_status_valid CHECK (status IN ('published', 'pending', 'hidden', 'removed')),
88 CONSTRAINT products_slug_format CHECK (slug ~ '^[a-z0-9][a-z0-9-]{0,79}$')
89);
90
91CREATE INDEX IF NOT EXISTS idx_products_status_published ON products(status, published_at DESC, created_at DESC);
92CREATE INDEX IF NOT EXISTS idx_products_owner_id ON products(owner_id);
93
94CREATE TABLE IF NOT EXISTS stars (
95 user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
96 product_id TEXT NOT NULL REFERENCES products(id) ON DELETE CASCADE,
97 created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
98 PRIMARY KEY (user_id, product_id)
99);
100
101CREATE INDEX IF NOT EXISTS idx_stars_product_id ON stars(product_id);
102
103ALTER TABLE users ADD COLUMN IF NOT EXISTS password_hash TEXT;
104
105CREATE TABLE IF NOT EXISTS upvotes (
106 user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
107 product_id TEXT NOT NULL REFERENCES products(id) ON DELETE CASCADE,
108 created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
109 PRIMARY KEY (user_id, product_id)
110);
111
112CREATE INDEX IF NOT EXISTS idx_upvotes_product_id ON upvotes(product_id);
113
114CREATE TABLE IF NOT EXISTS comments (
115 id TEXT PRIMARY KEY,
116 product_id TEXT NOT NULL REFERENCES products(id) ON DELETE CASCADE,
117 user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
118 body TEXT NOT NULL,
119 created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
120 CONSTRAINT comments_body_len CHECK (char_length(body) >= 1 AND char_length(body) <= 2000)
121);
122
123CREATE INDEX IF NOT EXISTS idx_comments_product_created ON comments(product_id, created_at ASC);
124CREATE INDEX IF NOT EXISTS idx_comments_user_created ON comments(user_id, created_at DESC);
125
126CREATE TABLE IF NOT EXISTS rate_limits (
127 id BIGSERIAL PRIMARY KEY,
128 action TEXT NOT NULL,
129 key TEXT NOT NULL,
130 created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
131);
132
133CREATE INDEX IF NOT EXISTS idx_rate_limits_lookup ON rate_limits(action, key, created_at DESC);
134`;
135
136export async function ensureSchema(): Promise<void> {
137 if (!isDatabaseConfigured()) return;
138 if (!globalThis.__hpSchemaReady) {
139 globalThis.__hpSchemaReady = getPool()
140 .query(SCHEMA_SQL)
141 .then(() => undefined)
142 .catch((err) => {
143 globalThis.__hpSchemaReady = undefined;
144 throw err;
145 });
146 }
147 return globalThis.__hpSchemaReady;
148}
149
150export async function query<T extends QueryResultRow = QueryResultRow>(
151 text: string,
152 params?: unknown[]
153): Promise<QueryResult<T>> {
154 await ensureSchema();
155 return getPool().query<T>(text, params);
156}
157
158export function readSchemaSqlFile(): string {
159 return fs.readFileSync(path.join(process.cwd(), "src/db/schema.sql"), "utf8");
160}
161
cg / hackerproducts — hacker products