koa-mongo-router
Version:
KOA REST API Router for MongoDB
59 lines (58 loc) • 1.98 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.PromiseTransformStream = void 0;
const stream_1 = require("stream");
const defaultTransformOptions = {
writableObjectMode: true,
readableObjectMode: true,
objectMode: true,
autoDestroy: false,
};
class PromiseTransformStream extends stream_1.Transform {
constructor(transform, concurrency = 100, options = defaultTransformOptions) {
super(options);
this.transform = transform;
this.concurrency = concurrency;
this.results = [];
this.pushIndex = 0;
this.activeCount = 0;
}
_transform(chunk, encoding, callback) {
const index = this.results.length;
this.results.push(null);
this.activeCount++;
if (this.activeCount === this.concurrency) {
this.resumeCallback = callback;
}
else {
callback();
}
void this.transform(chunk).then((item) => {
this.activeCount--;
this.results[index] = item;
while (this.results[this.pushIndex] != null && this.pushIndex < this.results.length) {
this.push(this.results[this.pushIndex]);
this.results[this.pushIndex] = undefined;
this.pushIndex++;
}
if (this.resumeCallback != undefined) {
const tempResumeCallback = this.resumeCallback;
this.resumeCallback = undefined;
tempResumeCallback();
}
if (this.endCallback != undefined && this.activeCount === 0) {
this.endCallback();
}
});
}
end(chunk, encoding, cb) {
if (this.results.length === 0) {
super.end(chunk, encoding, cb);
}
else {
this.endCallback = () => {
super.end(chunk, encoding, cb);
};
}
}
}
exports.PromiseTransformStream = PromiseTransformStream;