testCollectionsCheckTheirEntries

tcmts.content.test.testCollectionsCheckTheirEntries · #rulsxmqk · function

import { collection } from "#codebase/tcmts/content";
import { postSchema } from "#codebase/tcmts/content/test";
import assert from "node:assert/strict";

export const testCollectionsCheckTheirEntries = () => {
  const posts = collection(
    {
      old: "---\ntitle: Old\ndate: 2026-01-02\n---\nFirst.\n",
      new: "---\ntitle: New\ndate: 2026-11-07\n---\nSecond.\n",
    },
    { schema: postSchema, sort: (a, b) => b.data.date.localeCompare(a.data.date) },
  );
  assert.deepEqual(
    posts.all().map((e) => [e.name, e.data.title, e.body]),
    [
      ["new", "New", "Second.\n"],
      ["old", "Old", "First.\n"],
    ],
  );
  assert.equal(posts.get("old")?.data.date, "2026-01-02");
  assert.equal(posts.get("nothing"), undefined);
  // what's wrong, by where in the data; and what doesn't parse
  assert.deepEqual(posts.check("x", "---\ntitle: 3\n---\n"), [
    "title: a title, as text",
    "date: a day, YYYY-MM-DD",
  ]);
  assert.deepEqual(posts.check("x", "---\ntitle: T\ndate: 2026-11-07\n---\n"), []);
  assert.match(posts.check("x", "---\ntitle: [unclosed\n---\n")[0]!, /\S/);
  // tcm finds the check by its symbol
  const check = (posts as unknown as Record<symbol, (n: string, t: string) => string[]>)[
    Symbol.for("tcm.collection")
  ];
  assert.deepEqual(check?.("x", "---\ntitle: T\n---\n"), ["date: a day, YYYY-MM-DD"]);

  // one that doesn't fit is named when it's read, and only then
  const some = collection(
    { good: "---\ntitle: G\ndate: 2026-11-07\n---\n", bad: "---\ndate: soon\n---\n" },
    { schema: postSchema },
  );
  assert.equal(some.get("good")?.data.title, "G");
  assert.throws(() => some.all(), /bad: title: a title, as text; date: a day, YYYY-MM-DD/);
  assert.throws(() => some.get("bad"), /bad: title/);

  // JSON and YAML files are their data
  const people = collection(
    { ada: '{ "title": "Ada", "date": "1815-12-10" }' },
    { schema: postSchema, format: "json" },
  );
  assert.deepEqual(people.get("ada"), {
    name: "ada",
    data: { title: "Ada", date: "1815-12-10" },
    body: "",
    Content: undefined,
  });
  const yaml = collection(
    { a: "title: A\ndate: '2026-11-07'\n" },
    { schema: postSchema, format: "yaml" },
  );
  assert.equal(yaml.get("a")?.data.title, "A");
}

uses