fix: Consent API auto-creates database table on startup

- better-sqlite3 creates ConsentLog table if not exists
- Auto-creates data/ directory if missing
- Fixes Astro DB not creating custom tables issue
This commit is contained in:
Kunthawat Greethong
2026-03-31 11:44:31 +07:00
parent 36112e4137
commit 002966b739
3 changed files with 42 additions and 4 deletions

BIN
data/consent.db Normal file

Binary file not shown.

View File

@@ -1,13 +1,32 @@
import type { APIRoute } from 'astro';
import Database from 'better-sqlite3';
import { join } from 'path';
import { mkdirSync, existsSync } from 'fs';
export const prerender = false;
const DB_PATH = join(process.cwd(), 'data', 'consent.db');
const DATA_DIR = join(process.cwd(), 'data');
const DB_PATH = join(DATA_DIR, 'consent.db');
function getDb() {
return new Database(DB_PATH);
if (!existsSync(DATA_DIR)) {
mkdirSync(DATA_DIR, { recursive: true });
}
const db = new Database(DB_PATH);
db.exec(`
CREATE TABLE IF NOT EXISTS ConsentLog (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sessionId TEXT UNIQUE NOT NULL,
timestamp TEXT NOT NULL,
essential INTEGER NOT NULL DEFAULT 0,
analytics INTEGER NOT NULL DEFAULT 0,
marketing INTEGER NOT NULL DEFAULT 0,
policyVersion TEXT NOT NULL,
ipHash TEXT,
userAgent TEXT
)
`);
return db;
}
export const DELETE: APIRoute = async ({ params }) => {

View File

@@ -1,13 +1,32 @@
import type { APIRoute } from 'astro';
import Database from 'better-sqlite3';
import { join } from 'path';
import { mkdirSync, existsSync } from 'fs';
export const prerender = false;
const DB_PATH = join(process.cwd(), 'data', 'consent.db');
const DATA_DIR = join(process.cwd(), 'data');
const DB_PATH = join(DATA_DIR, 'consent.db');
function getDb() {
return new Database(DB_PATH);
if (!existsSync(DATA_DIR)) {
mkdirSync(DATA_DIR, { recursive: true });
}
const db = new Database(DB_PATH);
db.exec(`
CREATE TABLE IF NOT EXISTS ConsentLog (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sessionId TEXT UNIQUE NOT NULL,
timestamp TEXT NOT NULL,
essential INTEGER NOT NULL DEFAULT 0,
analytics INTEGER NOT NULL DEFAULT 0,
marketing INTEGER NOT NULL DEFAULT 0,
policyVersion TEXT NOT NULL,
ipHash TEXT,
userAgent TEXT
)
`);
return db;
}
const rateLimitMap = new Map<string, { count: number; resetTime: number }>();