test(core): added test cases for stream piping in http response
MODIFY
packages/core/src/+internal/utils/index.ts
packages/core/src/+internal/utils/index.ts
@@ -2,3 +2,4 @@ export * from './array.util';
export * from './string.util';
export * from './error.util';
export * from './any.util';
+export * from './stream.util';

ADD
packages/core/src/+internal/utils/stream.util.ts
+import * as stream from 'stream';
+
+export const isReadableStream = (data: any): data is stream.Readable =>
+ data instanceof stream.Readable;

MODIFY
packages/core/src/response/response.handler.ts
packages/core/src/response/response.handler.ts
-import * as stream from 'stream';
import { EMPTY } from 'rxjs';
import { HttpEffectResponse } from '../effects/http-effects.interface';
import { HttpRequest, HttpResponse, HttpStatus } from '../http.interface';
import { bodyFactory } from './responseBody.factory';
import { headersFactory } from './responseHeaders.factory';
+import { isReadableStream } from '../+internal/utils';
export const handleResponse = (res: HttpResponse) => (req: HttpRequest) => (effect: HttpEffectResponse) => {
if (res.finished) { return EMPTY; }
@@ -16,7 +16,7 @@ export const handleResponse = (res: HttpResponse) => (req: HttpRequest) => (effe
const bodyFactoryWithHeaders = bodyFactory(headers);
const body = bodyFactoryWithHeaders(effect.body);
- if (body instanceof stream.Readable) {
+ if (isReadableStream(body)) {
res.writeHead(status, headers);
body.pipe(res);
} else {

MODIFY
packages/core/src/response/specs/response.handler.spec.ts
packages/core/src/response/specs/response.handler.spec.ts
+import * as path from 'path';
+import * as fs from 'fs';
import { HttpRequest, HttpResponse, HttpStatus } from '../../http.interface';
import { handleResponse } from '../response.handler';
import { DEFAULT_HEADERS } from '../responseHeaders.factory';
+import { ContentType } from '../../+internal';
const createMockResponse = () => ({
writeHead: jest.fn(),
@@ -56,6 +59,20 @@ describe('Response handler', () => {
expect(response.end).toHaveBeenCalledWith(JSON.stringify({ foo: 'bar' }));
});
+ it('pipes body stream to response', () => {
+ // given
+ const pathToFile = path.resolve(__dirname, '../../../../../assets/media', 'audio.mp3');
+ const body = fs.createReadStream(pathToFile);
+ const headers = { 'Content-Type': ContentType.AUDIO_MPEG };
+
+ // when
+ jest.spyOn(body, 'pipe').mockImplementation(jest.fn);
+ handle({ body, headers });
+
+ // then
+ expect(body.pipe).toHaveBeenCalledWith(response);
+ });
+
it('returns immediately if response was finished', done => {
// given
response = { ...createMockResponse(), finished: true } as HttpResponse;

test(core): added test cases for stream piping in http response