45 lines
src/export/exportOrders.ts
Streams all order records as NDJSON, paginating through the database in fixed-size chunks.
// GET /admin/export/orders — streams all order records as NDJSON.
import type { Request, Response } from "express";
import { db } from "./db";
 
const PAGE_SIZE = 500;
 
// Serializes one row as an NDJSON line.
function toJsonLine(row: unknown): string {
  return JSON.stringify(row) + "\n";
}
 
/**
 * Streams every order record as newline-delimited JSON.
 *
 * Each record must appear exactly once even when concurrent writes
 * modify the dataset between page fetches.
 *
 * A database error during streaming must not leave the response open.
 * The error must be caught here; the function must resolve — not reject.
 */
// Streams order records to the HTTP response as NDJSON.
export async function exportOrders(
  req: Request,
  res: Response,
): Promise<void> {
  res.setHeader("Content-Type", "application/x-ndjson");
 
  let offset = 0;
 
  while (true) {
    const rows = await db.orders.fetchPage(offset, PAGE_SIZE);
 
    if (rows.length === 0) break;
 
    for (const row of rows) {
      res.write(toJsonLine(row));
    }
 
    offset += PAGE_SIZE;
 
    if (rows.length < PAGE_SIZE) break;
  }
 
  res.end();
}