UNPKG

2.3 kBJavaScriptView Raw
1"use strict";
2// Copyright IBM Corp. and LoopBack contributors 2017,2020. All Rights Reserved.
3// Node module: @loopback/rest
4// This file is licensed under the MIT License.
5// License text available at https://opensource.org/licenses/MIT
6Object.defineProperty(exports, "__esModule", { value: true });
7exports.writeResultToResponse = void 0;
8const stream_1 = require("stream");
9/**
10 * Writes the result from Application controller method
11 * into the HTTP response
12 *
13 * @param response - HTTP Response
14 * @param result - Result from the API to write into HTTP Response
15 */
16function writeResultToResponse(
17// not needed and responsibility should be in the sequence.send
18response,
19// result returned back from invoking controller method
20result) {
21 // Bypass response writing if the controller method returns `response` itself
22 // or the response headers have been sent
23 if (result === response || response.headersSent) {
24 return;
25 }
26 if (result === undefined) {
27 response.statusCode = 204;
28 response.end();
29 return;
30 }
31 const isStream = result instanceof stream_1.Readable || typeof (result === null || result === void 0 ? void 0 : result.pipe) === 'function';
32 if (isStream) {
33 response.setHeader('Content-Type', 'application/octet-stream');
34 // Stream
35 result.pipe(response);
36 return;
37 }
38 switch (typeof result) {
39 case 'object':
40 case 'boolean':
41 case 'number':
42 if (Buffer.isBuffer(result)) {
43 // Buffer for binary data
44 response.setHeader('Content-Type', 'application/octet-stream');
45 }
46 else {
47 // TODO(ritch) remove this, should be configurable
48 // See https://github.com/loopbackio/loopback-next/issues/436
49 response.setHeader('Content-Type', 'application/json');
50 // TODO(bajtos) handle errors - JSON.stringify can throw
51 result = JSON.stringify(result);
52 }
53 break;
54 default:
55 response.setHeader('Content-Type', 'text/plain');
56 result = result.toString();
57 break;
58 }
59 response.end(result);
60}
61exports.writeResultToResponse = writeResultToResponse;
62//# sourceMappingURL=writer.js.map
\No newline at end of file