refactor: Make piping consistent

This commit is contained in:
Joachim Van Herwegen
2020-11-10 16:02:49 +01:00
parent 715ba126f9
commit 95ab0b4e76
7 changed files with 56 additions and 25 deletions

View File

@@ -1,4 +1,5 @@
import { EventEmitter } from 'events';
import { PassThrough } from 'stream';
import type { MockResponse } from 'node-mocks-http';
import { createResponse } from 'node-mocks-http';
import streamifyArray from 'streamify-array';
@@ -66,4 +67,26 @@ describe('A BasicResponseWriter', (): void => {
expect(response._isEndCalled()).toBeTruthy();
expect(response._getStatusCode()).toBe(201);
});
it('can handle the data stream erroring.', async(): Promise<void> => {
const data = new PassThrough();
data.read = (): any => {
data.emit('error', new Error('bad data!'));
return null;
};
result = { statusCode: 201, data };
response = new PassThrough();
response.writeHead = jest.fn();
const end = new Promise((resolve): void => {
response.on('error', (error: Error): void => {
expect(error).toEqual(new Error('bad data!'));
resolve();
});
});
await expect(writer.handle({ response, result })).resolves.toBeUndefined();
await end;
});
});

View File

@@ -8,7 +8,7 @@ import {
decodeUriPathComponents,
encodeUriPathComponents,
ensureTrailingSlash,
matchingMediaType, pipeStreamsAndErrors, pushQuad,
matchingMediaType, pipeSafe, pushQuad,
readableToString,
toCanonicalUriPath,
} from '../../../src/util/Util';
@@ -48,19 +48,19 @@ describe('Util function', (): void => {
it('pipes data from one stream to the other.', async(): Promise<void> => {
const input = streamifyArray([ 'data' ]);
const output = new PassThrough();
pipeStreamsAndErrors(input, output);
await expect(readableToString(output)).resolves.toEqual('data');
const piped = pipeSafe(input, output);
await expect(readableToString(piped)).resolves.toEqual('data');
});
it('pipes errors from one stream to the other.', async(): Promise<void> => {
const input = streamifyArray([ 'data' ]);
const input = new PassThrough();
input.read = (): any => {
input.emit('error', new Error('error'));
return null;
};
const output = new PassThrough();
pipeStreamsAndErrors(input, output);
await expect(readableToString(output)).rejects.toThrow(new Error('error'));
const piped = pipeSafe(input, output);
await expect(readableToString(piped)).rejects.toThrow(new Error('error'));
});
it('supports mapping errors to something else.', async(): Promise<void> => {
@@ -70,8 +70,8 @@ describe('Util function', (): void => {
return null;
};
const output = new PassThrough();
pipeStreamsAndErrors(input, output, (): any => new Error('other error'));
await expect(readableToString(output)).rejects.toThrow(new Error('other error'));
const piped = pipeSafe(input, output, (): any => new Error('other error'));
await expect(readableToString(piped)).rejects.toThrow(new Error('other error'));
});
});