Allow CB to be called by construction streams

This commit is contained in:
Jerry Kurian
2019-08-29 14:39:08 -04:00
parent 9765e6cb49
commit 2524d51aa7
3 changed files with 17 additions and 20 deletions

View File

@@ -14,7 +14,9 @@ export function demux(
}
class Demux extends Writable {
private keyMap: object;
private keyMap: {
[key: string]: NodeJS.WritableStream | NodeJS.ReadWriteStream;
};
private demuxer: (chunk: any) => string;
private construct: (
destKey?: string,
@@ -28,22 +30,22 @@ class Demux extends Writable {
) {
super(options);
if (demuxBy.keyBy === undefined && demuxBy.key === undefined) {
throw new Error("Need one");
throw new Error(
"keyBy or key must be provided in second parameter",
);
}
this.demuxer = demuxBy.keyBy || ((chunk: any) => chunk[demuxBy.key!]);
this.construct = construct;
this.keyMap = {};
}
public write(chunk: any, encoding?: any, cb?: any): boolean {
public _write(chunk: any, encoding: string, cb: any) {
const destKey = this.demuxer(chunk);
if (this.keyMap[destKey] === undefined) {
this.keyMap[destKey] = this.construct(destKey);
this.keyMap[destKey] = this.construct(destKey).on("error", e => {
this.emit("error", e);
});
}
const writeRes = this.keyMap[destKey].write(chunk);
if (cb !== undefined) {
cb();
}
return writeRes;
return this.keyMap[destKey].write(chunk, encoding, cb);
}
}