|
| 1 | +import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs"; |
| 2 | +import { tmpdir } from "node:os"; |
| 3 | +import { join } from "node:path"; |
| 4 | +import { afterEach, beforeEach, describe, expect, it } from "vitest"; |
| 5 | +import { createDirectorySink } from "../../src/batch/services/directory-sink.js"; |
| 6 | + |
| 7 | +let dir: string; |
| 8 | + |
| 9 | +beforeEach(() => { |
| 10 | + dir = mkdtempSync(join(tmpdir(), "batch-dir-sink-")); |
| 11 | +}); |
| 12 | + |
| 13 | +afterEach(() => { |
| 14 | + rmSync(dir, { recursive: true, force: true }); |
| 15 | +}); |
| 16 | + |
| 17 | +describe("createDirectorySink", () => { |
| 18 | + it("writes one record file per item, named from the input", () => { |
| 19 | + const outDir = join(dir, "out"); |
| 20 | + const sink = createDirectorySink(outDir); |
| 21 | + |
| 22 | + sink.write({ index: 0, input: "https://a.com/x", ok: true, data: "A" }); |
| 23 | + sink.write({ |
| 24 | + index: 1, |
| 25 | + input: "https://b.com", |
| 26 | + ok: false, |
| 27 | + error: { class: "TimeoutError", message: "timed out" }, |
| 28 | + }); |
| 29 | + |
| 30 | + const files = readdirSync(outDir).sort(); |
| 31 | + expect(files).toEqual(["a.com-x.json", "b.com.json"]); |
| 32 | + |
| 33 | + const success = JSON.parse( |
| 34 | + readFileSync(join(outDir, "a.com-x.json"), "utf8") |
| 35 | + ); |
| 36 | + expect(success).toEqual({ |
| 37 | + index: 0, |
| 38 | + input: "https://a.com/x", |
| 39 | + result: "A", |
| 40 | + }); |
| 41 | + |
| 42 | + const failure = JSON.parse( |
| 43 | + readFileSync(join(outDir, "b.com.json"), "utf8") |
| 44 | + ); |
| 45 | + expect(failure).toEqual({ |
| 46 | + index: 1, |
| 47 | + input: "https://b.com", |
| 48 | + error: { class: "TimeoutError", message: "timed out" }, |
| 49 | + }); |
| 50 | + }); |
| 51 | + |
| 52 | + it("dedupes colliding names with a numeric suffix", () => { |
| 53 | + const sink = createDirectorySink(dir); |
| 54 | + |
| 55 | + sink.write({ index: 0, input: "not a url", ok: true, data: 1 }); |
| 56 | + sink.write({ index: 0, input: "also not a url", ok: true, data: 2 }); |
| 57 | + |
| 58 | + const files = readdirSync(dir).sort(); |
| 59 | + expect(files).toEqual(["item-0-2.json", "item-0.json"]); |
| 60 | + }); |
| 61 | +}); |
0 commit comments