feat: add SQLite-backed products store
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gwc3aCiyQxmCWQke8RvEz
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
const Database = require('better-sqlite3');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const SCHEMA = `
|
||||
CREATE TABLE IF NOT EXISTS products (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
url TEXT NOT NULL,
|
||||
last_price REAL,
|
||||
last_checked_at TEXT,
|
||||
last_check_status TEXT,
|
||||
created_at TEXT NOT NULL
|
||||
)`;
|
||||
|
||||
function openDb(dbPath) {
|
||||
if (dbPath !== ':memory:') {
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
}
|
||||
const db = new Database(dbPath);
|
||||
db.exec(SCHEMA);
|
||||
return db;
|
||||
}
|
||||
|
||||
function listProducts(db) {
|
||||
return db.prepare('SELECT * FROM products ORDER BY created_at ASC').all();
|
||||
}
|
||||
|
||||
function getProduct(db, id) {
|
||||
return db.prepare('SELECT * FROM products WHERE id = ?').get(id);
|
||||
}
|
||||
|
||||
function addProduct(db, { name, url }) {
|
||||
const createdAt = new Date().toISOString();
|
||||
const info = db.prepare(
|
||||
'INSERT INTO products (name, url, created_at) VALUES (?, ?, ?)'
|
||||
).run(name, url, createdAt);
|
||||
return getProduct(db, info.lastInsertRowid);
|
||||
}
|
||||
|
||||
function deleteProduct(db, id) {
|
||||
db.prepare('DELETE FROM products WHERE id = ?').run(id);
|
||||
}
|
||||
|
||||
function recordCheckSuccess(db, id, { price, checkedAt }) {
|
||||
db.prepare(
|
||||
'UPDATE products SET last_price = ?, last_checked_at = ?, last_check_status = ? WHERE id = ?'
|
||||
).run(price, checkedAt, 'ok', id);
|
||||
}
|
||||
|
||||
function recordCheckFailure(db, id, status) {
|
||||
db.prepare('UPDATE products SET last_check_status = ? WHERE id = ?').run(status, id);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
openDb, listProducts, getProduct, addProduct, deleteProduct,
|
||||
recordCheckSuccess, recordCheckFailure,
|
||||
};
|
||||
Reference in New Issue
Block a user