ToyShare/src/lib/db.ts

99 lines
2.9 KiB
TypeScript

import Database from 'better-sqlite3';
import path from 'path';
import { rawUsers, rawToys } from './mockData';
import type { User, Toy } from '@/types';
// Define the path for the database file in the project root
const dbPath = process.env.NODE_ENV === 'development'
? path.join(process.cwd(), 'toyshare.db')
: '/tmp/toyshare.db'; // Use a writable directory in other environments
// Add { verbose: console.log } for debugging SQL statements
const db = new Database(dbPath);
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
function initDb() {
// Check if the users table exists. If it does, we assume the DB is initialized.
const table = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name = 'users'").get();
if (!table) {
console.log("Database not found. Initializing and seeding...");
// Create Users Table
db.exec(`
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
nickname TEXT,
email TEXT NOT NULL UNIQUE,
role TEXT,
avatarUrl TEXT,
bio TEXT
);
`);
// Create Toys Table
db.exec(`
CREATE TABLE toys (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT NOT NULL,
category TEXT NOT NULL,
images TEXT,
unavailableRanges TEXT,
ownerId INTEGER NOT NULL,
pricePerDay REAL,
location TEXT,
FOREIGN KEY (ownerId) REFERENCES users(id) ON DELETE CASCADE
);
`);
console.log("Seeding initial data...");
// Prepare insert statements
const insertUser = db.prepare(`
INSERT INTO users (id, name, nickname, email, role, avatarUrl, bio)
VALUES (@id, @name, @nickname, @email, @role, @avatarUrl, @bio)
`);
const insertToy = db.prepare(`
INSERT INTO toys (id, name, description, category, images, unavailableRanges, ownerId, pricePerDay, location)
VALUES (@id, @name, @description, @category, @images, @unavailableRanges, @ownerId, @pricePerDay, @location)
`);
// Use a transaction for efficiency
const seedData = db.transaction(() => {
for (const user of rawUsers) {
insertUser.run({
id: user.id,
name: user.name,
nickname: user.nickname ?? null,
email: user.email,
role: user.role ?? 'User',
avatarUrl: user.avatarUrl ?? null,
bio: user.bio ?? null
});
}
for (const toy of rawToys) {
insertToy.run({
...toy,
images: JSON.stringify(toy.images),
unavailableRanges: JSON.stringify(toy.unavailableRanges),
});
}
});
seedData();
console.log("Database initialization and seeding complete.");
} else {
console.log("Database already initialized.");
}
}
// Initialize and export db
initDb();
export default db;