refactor: Let caller decide which error pipeStreamAndErrors should throw

This commit is contained in:
Joachim Van Herwegen 2020-09-25 09:53:19 +02:00
parent fa935cc4c7
commit 006f7ea7aa
2 changed files with 6 additions and 4 deletions

View File

@ -3,6 +3,7 @@ import rdfParser from 'rdf-parse';
import type { Representation } from '../../ldp/representation/Representation';
import { RepresentationMetadata } from '../../ldp/representation/RepresentationMetadata';
import { INTERNAL_QUADS } from '../../util/ContentTypes';
import { UnsupportedHttpError } from '../../util/errors/UnsupportedHttpError';
import { CONTENT_TYPE } from '../../util/UriConstants';
import { pipeStreamsAndErrors } from '../../util/Util';
import { checkRequest } from './ConversionUtil';
@ -39,7 +40,7 @@ export class RdfToQuadConverter extends TypedRepresentationConverter {
// Wrap the stream such that errors are transformed
// (Node 10 requires both writableObjectMode and readableObjectMode)
const data = new PassThrough({ writableObjectMode: true, readableObjectMode: true });
pipeStreamsAndErrors(rawQuads, data);
pipeStreamsAndErrors(rawQuads, data, (error): Error => new UnsupportedHttpError(error.message));
return {
binary: false,

View File

@ -2,7 +2,6 @@ import type { Readable, Writable } from 'stream';
import arrayifyStream from 'arrayify-stream';
import { DataFactory } from 'n3';
import type { Literal, NamedNode, Quad } from 'rdf-js';
import { UnsupportedHttpError } from './errors/UnsupportedHttpError';
/**
* Makes sure the input path has exactly 1 slash at the end.
@ -60,12 +59,14 @@ export const matchingMediaType = (mediaA: string, mediaB: string): boolean => {
* Makes sure an error of the first stream gets passed to the second.
* @param readable - Initial readable stream.
* @param destination - The destination for writing data.
* @param mapError - Optional function that takes the error and converts it to a new error.
*
* @returns The destination stream.
*/
export const pipeStreamsAndErrors = <T extends Writable>(readable: Readable, destination: T): T => {
export const pipeStreamsAndErrors = <T extends Writable>(readable: Readable, destination: T,
mapError?: (error: Error) => Error): T => {
readable.pipe(destination);
readable.on('error', (error): boolean => destination.emit('error', new UnsupportedHttpError(error.message)));
readable.on('error', (error): boolean => destination.emit('error', mapError ? mapError(error) : error));
return destination;
};