flecks/packages/core/src/server/stream.js

58 lines
1.2 KiB
JavaScript
Raw Normal View History

2022-03-01 01:52:56 -06:00
// eslint-disable-next-line max-classes-per-file
import JsonParse from 'jsonparse';
import {Transform} from 'stream';
export class JsonStream extends Transform {
constructor() {
super();
const self = this;
this.done = undefined;
this.parser = new JsonParse();
this.parser.onValue = function onValue(O) {
if (0 === this.stack.length) {
self.push(JSON.stringify(O));
self.done();
}
};
}
// eslint-disable-next-line no-underscore-dangle
_transform(chunk, encoding, done) {
this.done = done;
this.parser.write(chunk);
}
}
JsonStream.PrettyPrint = class extends Transform {
constructor(indent = 2) {
super();
this.indent = indent;
}
// eslint-disable-next-line no-underscore-dangle
async _transform(chunk, encoding, done) {
this.push(JSON.stringify(JSON.parse(chunk), null, this.indent));
done();
}
};
export const transform = (fn, opts = {}) => {
class EasyTransform extends Transform {
constructor() {
super(opts);
}
// eslint-disable-next-line no-underscore-dangle, class-methods-use-this
_transform(chunk, encoding, done) {
fn(chunk, encoding, done, this);
}
}
return new EasyTransform();
};