|
| 1 | +import { AsyncIterableX } from './asynciterablex'; |
| 2 | +import { OperatorAsyncFunction, UnaryFunction } from '../interfaces'; |
| 3 | +import { Transform, TransformCallback } from 'stream'; |
| 4 | + |
| 5 | +export interface TransformOptions { |
| 6 | + // ReadableOptions/WritableOptions |
| 7 | + highWaterMark?: number; |
| 8 | + objectMode?: boolean; |
| 9 | + autoDestroy?: boolean; |
| 10 | + // ReadableOptions |
| 11 | + encoding?: string; |
| 12 | + // WritableOptions |
| 13 | + decodeStrings?: boolean; |
| 14 | + defaultEncoding?: string; |
| 15 | + emitClose?: boolean; |
| 16 | + // DuplexOptions |
| 17 | + allowHalfOpen?: boolean; |
| 18 | + readableObjectMode?: boolean; |
| 19 | + writableObjectMode?: boolean; |
| 20 | + readableHighWaterMark?: number; |
| 21 | + writableHighWaterMark?: number; |
| 22 | + writableCorked?: number; |
| 23 | +} |
| 24 | + |
| 25 | +export interface AsyncIterableTransform<T> extends AsyncIterableX<T>, Transform { |
| 26 | + pipe<R>(...operations: UnaryFunction<AsyncIterable<T>, R>[]): R; |
| 27 | + pipe<R>(...operations: OperatorAsyncFunction<T, R>[]): AsyncIterableX<R>; |
| 28 | + pipe<R extends NodeJS.WritableStream>(writable: R, options?: { end?: boolean }): R; |
| 29 | + [Symbol.asyncIterator](): AsyncIterableIterator<T>; |
| 30 | +} |
| 31 | + |
| 32 | +const asyncIterableMixin = Symbol('asyncIterableMixin'); |
| 33 | + |
| 34 | +export class AsyncIterableTransform<T> extends Transform { |
| 35 | + private static [asyncIterableMixin] = false; |
| 36 | + constructor(options?: TransformOptions) { |
| 37 | + super(options); |
| 38 | + // If this is the first time AsyncIterableTransform is being constructed, |
| 39 | + // mixin the methods from the AsyncIterableX's prototype. |
| 40 | + if (!AsyncIterableTransform[asyncIterableMixin]) { |
| 41 | + AsyncIterableTransform[asyncIterableMixin] = true; |
| 42 | + Object.defineProperties( |
| 43 | + AsyncIterableTransform.prototype, |
| 44 | + Object.getOwnPropertyDescriptors(AsyncIterableX.prototype) |
| 45 | + ); |
| 46 | + } |
| 47 | + } |
| 48 | + /** @nocollapse */ |
| 49 | + _flush(callback: TransformCallback): void { |
| 50 | + callback(); |
| 51 | + } |
| 52 | + /** @nocollapse */ |
| 53 | + _transform(chunk: any, _encoding: string, callback: TransformCallback): void { |
| 54 | + callback(null, chunk); |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +export function asAsyncIterable<T>(options: TransformOptions = {}) { |
| 59 | + return new AsyncIterableTransform<T>(options); |
| 60 | +} |
0 commit comments