Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
## [0.1.2]

### FIX [SCMS] Prevent double response in lab-notes route 🧹

- Remove duplicate res.json call in /lab-notes handler
- Ensure handler returns after sending response
- Eliminate "Cannot set headers after they are sent" errors
- Stabilize test output and runtime behavior

## [0.1.1] – 2025-12-29

### Added
Expand Down
36 changes: 32 additions & 4 deletions src/db/migrateLabNotes.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,25 @@
// src/db/migrateLabNotes.ts
import Database from "better-sqlite3";

const LAB_NOTES_SCHEMA_VERSION = 1;

function getLabNotesSchemaVersion(db: Database.Database): number {
const row = db
.prepare(`SELECT value FROM schema_meta WHERE key='lab_notes_schema_version'`)
.get() as { value?: string } | undefined;

return row?.value ? Number(row.value) : 0;
}

function setLabNotesSchemaVersion(db: Database.Database, version: number) {
db.prepare(`
INSERT INTO schema_meta (key, value)
VALUES ('lab_notes_schema_version', ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value
`).run(String(version));
}


type ColDef = { name: string; ddl: string };
type MigrationLogFn = (msg: string) => void;

Expand Down Expand Up @@ -88,6 +107,14 @@ export function migrateLabNotesSchema(
}
}

db.exec(`
CREATE TABLE IF NOT EXISTS schema_meta (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
`);

const prevVersion = getLabNotesSchemaVersion(db);
// Backfills for legacy rows
db.exec(`
UPDATE lab_notes
Expand Down Expand Up @@ -174,14 +201,15 @@ export function migrateLabNotesSchema(
createdFreshTable: !hadLabNotesTable,
};

if (log && (result.createdFreshTable || result.addedColumns.length > 0)) {
if (log && (result.createdFreshTable || result.addedColumns.length > 0 || prevVersion !== LAB_NOTES_SCHEMA_VERSION)) {
const colsPart =
result.addedColumns.length > 0
? `added ${result.addedColumns.length} column(s): ${result.addedColumns.join(", ")}`
: "no new columns";
const tablePart = result.createdFreshTable ? "created lab_notes table" : "updated lab_notes table";
log(`[db] lab_notes migration: ${tablePart}; ${colsPart}`);
: "no column changes";

log(`[db] lab_notes migration: v${prevVersion} → v${LAB_NOTES_SCHEMA_VERSION}; ${colsPart}`);
}

setLabNotesSchemaVersion(db, LAB_NOTES_SCHEMA_VERSION);
return result;
}
17 changes: 7 additions & 10 deletions src/routes/labNotesRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import { marked } from "marked"; // npm i marked
export function registerLabNotesRoutes(app: any, db: Database.Database) {
// Public: Lab Notes list (preview)
app.get("/lab-notes", (_req: Request, res: Response) => {

try {
const notes = db.prepare(`
SELECT
Expand All @@ -22,26 +21,24 @@ export function registerLabNotesRoutes(app: any, db: Database.Database) {
FROM v_lab_notes
ORDER BY published_at DESC
`).all() as LabNoteRecord[];

const mapped = notes.map((note) => {
const tagRows = db
.prepare("SELECT tag FROM lab_note_tags WHERE note_id = ?")
.all(note.id) as TagResult[];

return mapToLabNotePreview(note, tagRows.map((t) => t.tag));
});
res.json(mapped);
res.json(notes);

return res.json(mapped);
} catch (e: any) {
console.error("GET /lab-notes failed:", e?.message);
res.status(500).json({ error: e?.message ?? "unknown" });
}






if (res.headersSent) return;
return res.status(500).json({ error: e?.message ?? "unknown" });
}
});


// Public: single Lab Note (detail)
app.get("/lab-notes/:slug", (req: Request, res: Response) => {
Expand Down
109 changes: 109 additions & 0 deletions tests/db.migrateLabNotes.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import Database from "better-sqlite3";
import { migrateLabNotesSchema } from "../src/db/migrateLabNotes.js";

function openMemoryDb() {
return new Database(":memory:");
}

function tableExists(db: Database.Database, name: string) {
const row = db
.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name=?`)
.get(name) as { name?: string } | undefined;
return !!row?.name;
}

function viewExists(db: Database.Database, name: string) {
const row = db
.prepare(`SELECT name FROM sqlite_master WHERE type='view' AND name=?`)
.get(name) as { name?: string } | undefined;
return !!row?.name;
}

function getCols(db: Database.Database, table: string): string[] {
return db.prepare(`PRAGMA table_info(${table})`).all().map((r: any) => r.name);
}

function getSchemaVersion(db: Database.Database): number {
const row = db
.prepare(`SELECT value FROM schema_meta WHERE key='lab_notes_schema_version'`)
.get() as { value?: string } | undefined;
return row?.value ? Number(row.value) : 0;
}

describe("migrateLabNotesSchema", () => {
test("fresh DB: creates schema, view, tag table, and sets schema version", () => {
const db = openMemoryDb();

const logs: string[] = [];
const res = migrateLabNotesSchema(db, (m) => logs.push(m));

expect(tableExists(db, "lab_notes")).toBe(true);
expect(viewExists(db, "v_lab_notes")).toBe(true);
expect(tableExists(db, "schema_meta")).toBe(true);
expect(tableExists(db, "lab_note_tags")).toBe(true);

// a couple key columns should exist
const cols = getCols(db, "lab_notes");
expect(cols).toContain("content_md");
expect(cols).toContain("translation_status");
expect(cols).toContain("department_id");

// version should be set
expect(getSchemaVersion(db)).toBeGreaterThan(0);

// should have logged something on a fresh DB
expect(res.createdFreshTable).toBe(true);
expect(logs.length).toBeGreaterThan(0);

db.close();
});

test("existing minimal lab_notes table: adds missing columns and preserves rows + backfills group_id", () => {
const db = openMemoryDb();

// simulate an old DB that only had id
db.exec(`
CREATE TABLE lab_notes (id TEXT PRIMARY KEY);
INSERT INTO lab_notes (id) VALUES ('n1');
`);

const res = migrateLabNotesSchema(db);

// row preserved
const row = db.prepare(`SELECT id, group_id FROM lab_notes WHERE id='n1'`).get() as any;
expect(row.id).toBe("n1");
expect(row.group_id).toBe("n1"); // backfilled

// should have added columns
expect(res.addedColumns.length).toBeGreaterThan(0);

db.close();
});

test("idempotent: second run adds no columns and does not throw", () => {
const db = openMemoryDb();

const first = migrateLabNotesSchema(db);
const second = migrateLabNotesSchema(db);

expect(first.createdFreshTable).toBe(true);
expect(second.createdFreshTable).toBe(false);
expect(second.addedColumns).toEqual([]);

db.close();
});

test("logger: logs only when changes occur", () => {
const db = openMemoryDb();

const logs1: string[] = [];
migrateLabNotesSchema(db, (m) => logs1.push(m));
expect(logs1.length).toBeGreaterThan(0);

const logs2: string[] = [];
migrateLabNotesSchema(db, (m) => logs2.push(m));
expect(logs2.length).toBe(0);

db.close();
});
});