Skip to content

Commit

Permalink
http/endpoint: extract common pipe code (#1113)
Browse files Browse the repository at this point in the history
defaultResultWriter and odataJsonWriter use identical code for piping results to
response.  This commit extracts the shared code into its own function.
  • Loading branch information
alxndrsn authored Oct 8, 2024
1 parent 0802210 commit a4af6f0
Showing 1 changed file with 14 additions and 13 deletions.
27 changes: 14 additions & 13 deletions lib/http/endpoint.js
Original file line number Diff line number Diff line change
Expand Up @@ -191,21 +191,27 @@ 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;
}
return false;
};

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 {
Expand Down Expand Up @@ -349,16 +355,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);
Expand Down

0 comments on commit a4af6f0

Please sign in to comment.