← back to Govarbitrage

src/lib/listings-sort.test.ts

59 lines

import { describe, it, expect } from "vitest";
import { Prisma } from "@prisma/client";

// Regression guard for TK-11464: sorting the listings grid by a non-nullable
// native column (title, source, condition, …) returned HTTP 500 because the
// DB-side orderBy applied Prisma's { sort, nulls } object form to EVERY native
// column. Prisma only accepts that object form on OPTIONAL (nullable) fields;
// a required field must use the bare SortOrder string, else it throws
// PrismaClientValidationError ("Expected SortOrder, provided Object.").
//
// listings.ts gates the object form behind NULLABLE_NATIVE_SORT_COLUMNS. This
// test keeps that gate honest against the schema with no DB needed: a native
// column is classified nullable iff the Prisma field is optional. It fails if
// a field's nullability changes without updating the set, or a new native sort
// column is added unclassified.

// Mirror of the sets in src/lib/listings.ts (this test is their sync-check).
const NATIVE_SORT_COLUMNS = [
  "currentBid",
  "closingAt",
  "title",
  "source",
  "sourceAuctionId",
  "category",
  "manufacturer",
  "model",
  "condition",
  "quantity",
  "researchStatus",
  "createdAt",
] as const;

const NULLABLE_NATIVE_SORT_COLUMNS = new Set<string>([
  "closingAt",
  "category",
  "manufacturer",
  "model",
]);

describe("listings native sort classification (TK-11464)", () => {
  const listing = Prisma.dmmf.datamodel.models.find((m) => m.name === "Listing");

  it("resolves the Listing model from the Prisma DMMF", () => {
    expect(listing).toBeDefined();
  });

  it("classifies a native sort column as nullable iff the schema field is optional", () => {
    for (const name of NATIVE_SORT_COLUMNS) {
      const field = listing!.fields.find((f) => f.name === name);
      expect(field, `${name} is not a scalar field on Listing`).toBeDefined();
      // Prisma: optional field => isRequired === false => may carry { sort, nulls }.
      expect(
        NULLABLE_NATIVE_SORT_COLUMNS.has(name),
        `${name}: orderBy nullability classification must match schema (schema optional=${!field!.isRequired})`,
      ).toBe(!field!.isRequired);
    }
  });
});