diff --git a/lib/http/endpoint.js b/lib/http/endpoint.js index a405abf31..fb17b971b 100644 --- a/lib/http/endpoint.js +++ b/lib/http/endpoint.js @@ -192,20 +192,28 @@ const endpointBase = ({ preprocessor = noop, before = noop, resultWriter, errorW // ENDPOINT FORMAT SPECIALIZATIONS //////////////////////////////////////// -// JSON/default const streamErrorHandler = (response) => () => { response.addTrailers({ Status: 'Error' }); // TODO: improve response content. }; -const defaultResultWriter = (result, request, response, next) => { - if (!response.hasHeader('Content-Type')) response.type('json'); - +const pipelineResult = (result, response, next) => { if (result instanceof PartialPipe) { result.streams.at(-1).on('error', streamErrorHandler(response)); result.with(response).pipeline((err) => next?.(err)); + return true; } else if (result.pipe != null) { result.on('error', streamErrorHandler(response)); pipeline(result, response, (err) => err && next?.(err)); + return true; + } +}; + +// JSON/default +const defaultResultWriter = (result, request, response, next) => { + if (!response.hasHeader('Content-Type')) response.type('json'); + + if (pipelineResult(result, response, next)) { + // handled } else if (isJsonType(response.getHeader('Content-Type'))) { response.send(jsonSerialize(result)); } else { @@ -349,16 +357,11 @@ const odataPreprocessor = (format) => (_, context) => { // respond with the appropriate OData version (section 8.1.5). const odataBefore = (response) => { response.setHeader('OData-Version', '4.0'); }; -// TODO refactor to share common code with defaultResultWriter? const odataJsonWriter = (result, request, response, next) => { if (!response.hasHeader('Content-Type')) response.type('json'); - if (result instanceof PartialPipe) { - result.streams.at(-1).on('error', streamErrorHandler(response)); - result.with(response).pipeline((err) => next?.(err)); - } else if (result.pipe != null) { - result.on('error', streamErrorHandler(response)); - pipeline(result, response, (err) => err && next?.(err)); + if (pipelineResult(result, response, next)) { + // handled } else { // OData JSON endpoints craft JSON by hand response.send(result);