MCPcopy Index your code
hub / github.com/loopbackio/loopback-next / writeResultToResponse

Function writeResultToResponse

packages/rest/src/writer.ts:16–63  ·  view source on GitHub ↗
(
  // not needed and responsibility should be in the sequence.send
  response: Response,
  // result returned back from invoking controller method
  result: OperationRetval,
)

Source from the content-addressed store, hash-verified

14 * @param result - Result from the API to write into HTTP Response
15 */
16export function writeResultToResponse(
17 // not needed and responsibility should be in the sequence.send
18 response: Response,
19 // result returned back from invoking controller method
20 result: OperationRetval,
21): void {
22 // Bypass response writing if the controller method returns `response` itself
23 // or the response headers have been sent
24 if (result === response || response.headersSent) {
25 return;
26 }
27 if (result === undefined) {
28 response.statusCode = 204;
29 response.end();
30 return;
31 }
32
33 const isStream =
34 result instanceof Readable || typeof result?.pipe === 'function';
35
36 if (isStream) {
37 response.setHeader('Content-Type', 'application/octet-stream');
38 // Stream
39 result.pipe(response);
40 return;
41 }
42 switch (typeof result) {
43 case 'object':
44 case 'boolean':
45 case 'number':
46 if (Buffer.isBuffer(result)) {
47 // Buffer for binary data
48 response.setHeader('Content-Type', 'application/octet-stream');
49 } else {
50 // TODO(ritch) remove this, should be configurable
51 // See https://github.com/loopbackio/loopback-next/issues/436
52 response.setHeader('Content-Type', 'application/json');
53 // TODO(bajtos) handle errors - JSON.stringify can throw
54 result = JSON.stringify(result);
55 }
56 break;
57 default:
58 response.setHeader('Content-Type', 'text/plain');
59 result = result.toString();
60 break;
61 }
62 response.end(result);
63}

Callers 1

writer.unit.tsFile · 0.85

Calls 2

endMethod · 0.45
toStringMethod · 0.45

Tested by

no test coverage detected