import { afterEach, describe, expect, it, vi } from "vitest"; import type { ExportSchema } from "../../types"; import { buildAirtableFields, deleteAirtableRecords, mapItemToFields, upsertAirtableRecords, } from "../handler"; import type { AirtableExportConfig } from "../types"; const config: AirtableExportConfig = { baseId: "appXXXXXXXXXXXXXX", tableId: "tblXXXXXXXXXXXXXX", fieldMapping: { title: "Name" }, createdByUpstart: true, fields: [ { id: "fld1", name: "Name", type: "singleLineText" }, { id: "fld2", name: "count", type: "number" }, { id: "fld3", name: "done", type: "checkbox" }, { id: "fld4", name: "tags", type: "multipleSelects" }, ], }; type FetchCall = { url: string; method: string; body: unknown }; function mockFetch(responder: (call: FetchCall, index: number) => { status: number; body: unknown }) { const calls: FetchCall[] = []; const fetchMock = vi.fn(async (url: string, init?: RequestInit) => { const call: FetchCall = { url, method: init?.method ?? "GET", body: init?.body ? JSON.parse(init.body as string) : null, }; calls.push(call); const { status, body } = responder(call, calls.length - 1); return { ok: status >= 200 && status < 300, status, json: async () => body, } as Response; }); vi.stubGlobal("fetch", fetchMock); return calls; } afterEach(() => { vi.unstubAllGlobals(); }); describe("mapItemToFields", () => { it("applies the field mapping and coerces values to the remote field types", () => { const fields = mapItemToFields({ title: "Hello", count: "42", done: "true", tags: "a, b" }, config); expect(fields).toEqual({ Name: "Hello", count: 42, done: true, tags: ["a", "b"] }); }); it("skips properties with no matching remote field instead of failing the batch", () => { expect(mapItemToFields({ unknownProperty: "x", count: 1 }, config)).toEqual({ count: 1 }); }); it("keeps already-typed values untouched", () => { expect(mapItemToFields({ count: 3, done: false, tags: ["x"] }, config)).toEqual({ count: 3, done: false, tags: ["x"], }); }); }); describe("buildAirtableFields", () => { const schema: ExportSchema = { properties: { email: { type: "string", format: "email", metadata: { order: 1 } }, published: { type: "boolean", metadata: { order: 0 } }, score: { type: "number" }, status: { type: "string", enum: ["draft", "live"] }, }, }; it("maps JSON Schema properties to Airtable field types", () => { const fields = buildAirtableFields(schema); const byName = Object.fromEntries(fields.map((field) => [field.name, field.type])); expect(byName).toMatchObject({ email: "email", published: "checkbox", score: "number", status: "singleSelect", }); }); it("honours metadata.order and puts ordered properties first", () => { const names = buildAirtableFields(schema).map((field) => field.name); expect(names.slice(0, 2)).toEqual(["published", "email"]); }); }); describe("upsertAirtableRecords", () => { it("creates new records in batches of 10", async () => { const items = Array.from({ length: 23 }, (_, index) => ({ itemId: `item-${index}`, data: { title: `Row ${index}` }, externalRecordId: null, })); const calls = mockFetch((call) => ({ status: 200, body: { records: (call.body as { records: unknown[] }).records.map((_, index) => ({ id: `rec${index}`, fields: {}, })), }, })); const results = await upsertAirtableRecords({ accessToken: "tok", config, items }); expect(calls).toHaveLength(3); expect(calls.every((call) => call.method === "POST")).toBe(true); expect((calls[0].body as { records: unknown[] }).records).toHaveLength(10); expect((calls[2].body as { records: unknown[] }).records).toHaveLength(3); expect(results).toHaveLength(23); expect(results.every((result) => result.externalRecordId && !result.error)).toBe(true); }); it("patches records that already exist remotely", async () => { const calls = mockFetch(() => ({ status: 200, body: { records: [{ id: "rec1", fields: {} }] } })); const results = await upsertAirtableRecords({ accessToken: "tok", config, items: [{ itemId: "item-1", data: { title: "x" }, externalRecordId: "rec1" }], }); expect(calls[0].method).toBe("PATCH"); expect((calls[0].body as { records: { id: string }[] }).records[0].id).toBe("rec1"); expect(results[0]).toEqual({ itemId: "item-1", externalRecordId: "rec1" }); }); it("reports every item of a failed batch in error", async () => { mockFetch(() => ({ status: 422, body: { error: { type: "INVALID_VALUE", message: "bad value" } }, })); const results = await upsertAirtableRecords({ accessToken: "tok", config, items: [ { itemId: "a", data: { title: "a" }, externalRecordId: null }, { itemId: "b", data: { title: "b" }, externalRecordId: null }, ], }); expect(results).toHaveLength(2); expect(results.every((result) => result.error?.includes("bad value"))).toBe(true); }); it("recreates the rows Airtable reports as deleted, and updates the others", async () => { // Deleting a row in Airtable is permanent; the error names the offending id, so // that record is peeled off, the rest of the batch is retried, and the missing one // is recreated in the same run. const calls = mockFetch((call) => { if (call.method === "PATCH") { const ids = (call.body as { records: { id: string }[] }).records.map((record) => record.id); if (ids.includes("recGone")) { return { status: 422, body: { error: { type: "ROW_DOES_NOT_EXIST", message: "Record ID recGone does not exist in this table", }, }, }; } return { status: 200, body: { records: ids.map((id) => ({ id, fields: {} })) } }; } return { status: 200, body: { records: [{ id: "recNew", fields: {} }] } }; }); const results = await upsertAirtableRecords({ accessToken: "tok", config, items: [ { itemId: "a", data: { title: "a" }, externalRecordId: "recGone" }, { itemId: "b", data: { title: "b" }, externalRecordId: "recAlive" }, ], }); expect(calls.map((call) => call.method)).toEqual(["PATCH", "PATCH", "POST"]); expect(results).toContainEqual({ itemId: "b", externalRecordId: "recAlive" }); expect(results).toContainEqual({ itemId: "a", externalRecordId: "recNew" }); }); it("keeps the stored record ids when a batch update fails", async () => { // Airtable fails a batch atomically without naming the culprit: forgetting the ids // would duplicate every record of the batch on the next run. mockFetch(() => ({ status: 404, body: { error: { type: "MODEL_ID_NOT_FOUND" } } })); const results = await upsertAirtableRecords({ accessToken: "tok", config, items: [ { itemId: "a", data: { title: "a" }, externalRecordId: "recGone" }, { itemId: "b", data: { title: "b" }, externalRecordId: "recStillThere" }, ], }); expect(results).toHaveLength(2); expect(results.every((result) => result.error && !result.resetExternalRecordId)).toBe(true); }); }); describe("deleteAirtableRecords", () => { it("deletes in batches of 10 using query parameters", async () => { const calls = mockFetch(() => ({ status: 200, body: { records: [] } })); const recordIds = Array.from({ length: 12 }, (_, index) => `rec${index}`); await deleteAirtableRecords({ accessToken: "tok", config, recordIds }); expect(calls).toHaveLength(2); expect(calls[0].method).toBe("DELETE"); expect(calls[0].url.split("records[]=").length - 1).toBe(10); expect(calls[1].url.split("records[]=").length - 1).toBe(2); }); it("ignores records already gone remotely", async () => { mockFetch(() => ({ status: 404, body: { error: "NOT_FOUND" } })); await expect( deleteAirtableRecords({ accessToken: "tok", config, recordIds: ["rec1"] }), ).resolves.toBeUndefined(); }); });