65 lines
2.1 KiB
TypeScript
65 lines
2.1 KiB
TypeScript
import { getDb } from '../db/connection.js';
|
|
import { ulid } from 'ulid';
|
|
|
|
export function listNotes(recipeId: string, userId?: string) {
|
|
const db = getDb();
|
|
|
|
if (!userId) {
|
|
// Legacy: return all notes without user filtering
|
|
return db.prepare('SELECT * FROM notes WHERE recipe_id = ? AND user_id IS NULL ORDER BY created_at DESC').all(recipeId);
|
|
}
|
|
|
|
// Return only user's notes
|
|
return db.prepare('SELECT * FROM notes WHERE recipe_id = ? AND user_id = ? ORDER BY created_at DESC').all(recipeId, userId);
|
|
}
|
|
|
|
export function createNote(recipeId: string, content: string, userId?: string) {
|
|
const db = getDb();
|
|
const recipe = db.prepare('SELECT id FROM recipes WHERE id = ?').get(recipeId);
|
|
if (!recipe) return null;
|
|
|
|
const id = ulid();
|
|
db.prepare('INSERT INTO notes (id, recipe_id, content, user_id) VALUES (?, ?, ?, ?)').run(id, recipeId, content, userId || null);
|
|
return db.prepare('SELECT * FROM notes WHERE id = ?').get(id);
|
|
}
|
|
|
|
export function updateNote(id: string, content: string, userId?: string) {
|
|
const db = getDb();
|
|
|
|
let query: string;
|
|
let params: any[];
|
|
|
|
if (!userId) {
|
|
// Legacy: update notes without user filtering
|
|
query = 'UPDATE notes SET content = ? WHERE id = ? AND user_id IS NULL';
|
|
params = [content, id];
|
|
} else {
|
|
// Update only if note belongs to user
|
|
query = 'UPDATE notes SET content = ? WHERE id = ? AND user_id = ?';
|
|
params = [content, id, userId];
|
|
}
|
|
|
|
const result = db.prepare(query).run(...params);
|
|
if (result.changes === 0) return null;
|
|
return db.prepare('SELECT * FROM notes WHERE id = ?').get(id);
|
|
}
|
|
|
|
export function deleteNote(id: string, userId?: string): boolean {
|
|
const db = getDb();
|
|
|
|
let query: string;
|
|
let params: any[];
|
|
|
|
if (!userId) {
|
|
// Legacy: delete notes without user filtering
|
|
query = 'DELETE FROM notes WHERE id = ? AND user_id IS NULL';
|
|
params = [id];
|
|
} else {
|
|
// Delete only if note belongs to user
|
|
query = 'DELETE FROM notes WHERE id = ? AND user_id = ?';
|
|
params = [id, userId];
|
|
}
|
|
|
|
return db.prepare(query).run(...params).changes > 0;
|
|
}
|