63 lines
2.2 KiB
TypeScript
63 lines
2.2 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
|
import { sanitizeDocument } from "./sanitize.js";
|
|
import type { SearchIndexSchema } from "./schemas/types.js";
|
|
|
|
const schema: SearchIndexSchema = {
|
|
name: "test-index",
|
|
primaryKey: "id",
|
|
searchableAttributes: ["title"],
|
|
filterableAttributes: ["tenantId"],
|
|
sortableAttributes: [],
|
|
allowedDocumentFields: ["id", "tenantId", "title", "tags"],
|
|
};
|
|
|
|
describe("sanitizeDocument", () => {
|
|
it("keeps only schema-allowed fields and preserves the required scope keys", () => {
|
|
expect(
|
|
sanitizeDocument(schema, {
|
|
id: "row_1",
|
|
tenantId: "tenant_1",
|
|
title: "Visible title",
|
|
tags: ["public"],
|
|
email: "private@example.test",
|
|
apiKey: "secret",
|
|
nested: { token: "hidden" },
|
|
})
|
|
).toEqual({
|
|
id: "row_1",
|
|
tenantId: "tenant_1",
|
|
title: "Visible title",
|
|
tags: ["public"],
|
|
});
|
|
});
|
|
|
|
it("accepts numeric primary keys but rejects missing or non-scalar primary keys", () => {
|
|
expect(sanitizeDocument(schema, { id: 42, tenantId: "tenant_1", title: "Number id" })).toMatchObject({
|
|
id: 42,
|
|
tenantId: "tenant_1",
|
|
});
|
|
|
|
expect(() => sanitizeDocument(schema, { tenantId: "tenant_1", title: "Missing id" })).toThrow(
|
|
'Document for index "test-index" is missing primary key "id".'
|
|
);
|
|
expect(() => sanitizeDocument(schema, { id: { nested: true }, tenantId: "tenant_1", title: "Bad id" })).toThrow(
|
|
'Document primary key "id" must be string or number.'
|
|
);
|
|
});
|
|
|
|
it("fails loudly when tenantId is missing, empty, or not schema-allowed", () => {
|
|
expect(() => sanitizeDocument(schema, { id: "row_1", title: "Missing tenant" })).toThrow(
|
|
'Document for index "test-index" is missing required tenantId.'
|
|
);
|
|
expect(() => sanitizeDocument(schema, { id: "row_1", tenantId: "", title: "Empty tenant" })).toThrow(
|
|
'Document for index "test-index" is missing required tenantId.'
|
|
);
|
|
expect(() =>
|
|
sanitizeDocument(
|
|
{ ...schema, allowedDocumentFields: ["id", "title"] },
|
|
{ id: "row_1", tenantId: "tenant_1", title: "Tenant stripped by schema" }
|
|
)
|
|
).toThrow('Document for index "test-index" is missing required tenantId.');
|
|
});
|
|
});
|