Skip to content

Commit

Permalink
propagate error between steams
Browse files Browse the repository at this point in the history
  • Loading branch information
tasshi-me committed Feb 14, 2023
1 parent 7a77a54 commit 34b13e4
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
11 changes: 7 additions & 4 deletions src/record/import/repositories/parsers/parseCsv/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import type { CsvRow } from "../../../../../kintone/types";
import type { LocalRecord } from "../../../types/record";
import type { RecordSchema } from "../../../types/schema";

// import csvParse from "csv-parse/lib/sync";
import csvParse from "csv-parse";

import { convertRecord, recordReader } from "./record";
Expand All @@ -17,13 +14,17 @@ export async function* csvReader<T extends NodeJS.ReadableStream>(
schema: RecordSchema
): ReturnType<LocalRecordRepository["reader"]> {
try {
const sourceStream = source();
const csvStream = source().pipe(
csvParse({
columns: true,
skip_empty_lines: true,
delimiter: SEPARATOR,
})
);
sourceStream.on("error", (e) => {
csvStream.destroy(e);
});

for await (const recordRows of recordReader(csvStream)) {
yield convertRecord(recordRows, schema);
Expand All @@ -45,14 +46,16 @@ export const countRecordsFromCsv = async <T extends NodeJS.ReadableStream>(
delimiter: SEPARATOR,
})
);
source.on("error", (e) => {
csvStream.destroy(e);
});

let count = 0;
for await (const recordRows of recordReader(csvStream)) {
count++;
}
return count;
} catch (e) {
console.error(e);
throw new ParserError(e);
}
};
20 changes: 15 additions & 5 deletions src/record/import/utils/file.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,34 @@
import fs from "fs";
import path from "path";
import iconv from "iconv-lite";
import { Transform } from "stream";

export type SupportedImportEncoding = "utf8" | "sjis";

export const openFsStreamWithEncode: (
filePath: string,
encoding?: SupportedImportEncoding
) => { stream: NodeJS.ReadWriteStream; format: string } = (
) => { stream: NodeJS.ReadableStream; format: string } = (
filePath,
encoding = "utf8"
) => {
const format = extractFileFormat(filePath);
if (format === "json" && encoding !== "utf8") {
throw new Error("source file is JSON and JSON MUST be encoded with UTF-8");
}
const stream = fs
.createReadStream(filePath)
.pipe(iconv.decodeStream(encoding));
return { stream, format };
const stream = fs.createReadStream(filePath);

const decodedStream = stream.pipe(
Transform.from(iconv.decodeStream(encoding))
);
stream.on("error", (e) => {
decodedStream.destroy(e);
});

decodedStream.on("error", () => {
/* noop. but this is necessary :) */
});
return { stream: decodedStream, format };
};

export const readFile: (
Expand Down

0 comments on commit 34b13e4

Please sign in to comment.