exportRows

tcmts.studio.exportRows · #zkotzzs6 · term · runs on the server

uses tcmts.studio.editableCodebase, which uses tcmts.share.servedCodebase, which uses process

A table's rows as the page shows them (q searched, where filtered, sort ordered; up to 10,000), as a file to download: JSON (each row its id and value, as toJson writes it) or CSV (a column a field, as its cells read).

import { dataPage } from "#codebase/tcmts/cli/data_pages";
import { editableCodebase } from "#codebase/tcmts/studio";

export async function exportRows(
  table: string,
  q: string,
  where: Record<string, string>,
  sort: string,
  desc: boolean,
  format: "json" | "csv",
): Promise<string> {
  const cb = editableCodebase();
  const d = dataPage(cb, table, {
    offset: 0,
    limit: 10_000,
    ...(q ? { search: q } : {}),
    ...(Object.keys(where).length ? { where } : {}),
    ...(sort ? { sort: { field: sort, desc } } : {}),
  });
  if (format === "json")
    return `${JSON.stringify(
      d.rows.map((r) => ({
        id: r.id,
        ...(r.json && typeof r.json === "object" ? r.json : { value: r.json }),
      })),
      null,
      2,
    )}\n`;
  const csv = (s: string) => (/[",\n]/.test(s) ? `"${s.replaceAll('"', '""')}"` : s);
  const head = ["id", ...d.fields.map((f) => f.name), "updated"];
  const lines = d.rows.map((r) =>
    [r.id, ...d.fields.map((f) => r.cells[f.name] ?? ""), new Date(r.updated).toISOString()]
      .map(csv)
      .join(","),
  );
  return `${[head.map(csv).join(","), ...lines].join("\n")}\n`;
}

uses

used by