UNPKG

2.92 kBJavaScriptView Raw
1"use strict";
2// Copyright IBM Corp. 2018,2020. All Rights Reserved.
3// Node module: @loopback/testlab
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.givenHttpServerConfig = void 0;
8const tslib_1 = require("tslib");
9const assert_1 = tslib_1.__importDefault(require("assert"));
10const fs_1 = require("fs");
11const path_1 = tslib_1.__importDefault(require("path"));
12const FIXTURES = path_1.default.resolve(__dirname, '../fixtures');
13const DUMMY_TLS_CONFIG = {
14 key: (0, fs_1.readFileSync)(path_1.default.join(FIXTURES, 'key.pem')),
15 cert: (0, fs_1.readFileSync)(path_1.default.join(FIXTURES, 'cert.pem')),
16};
17/**
18 * Assertion type guard for TypeScript to ensure `host` and `port` are set
19 * @param config - Host/port configuration
20 */
21function assertHostPort(config) {
22 (0, assert_1.default)(config.host != null, 'host is not set');
23 (0, assert_1.default)(config.port != null, 'port is not set');
24}
25/**
26 * Create an HTTP-server configuration that works well in test environments.
27 * - Ask the operating system to assign a free (ephemeral) port.
28 * - Use IPv4 localhost `127.0.0.1` to avoid known IPv6 issues in Docker-based
29 * environments like Travis-CI.
30 * - Provide default TLS key & cert when `protocol` is set to `https`.
31 *
32 * @param customConfig - Additional configuration options to apply.
33 */
34function givenHttpServerConfig(customConfig) {
35 const defaults = { host: '127.0.0.1', port: 0 };
36 if (isHttpsConfig(customConfig)) {
37 const config = { ...customConfig };
38 if (config.host == null)
39 config.host = defaults.host;
40 if (config.port == null)
41 config.port = defaults.port;
42 setupTlsConfig(config);
43 assertHostPort(config);
44 return config;
45 }
46 assertHttpConfig(customConfig);
47 const config = { ...customConfig };
48 if (config.host == null)
49 config.host = defaults.host;
50 if (config.port == null)
51 config.port = defaults.port;
52 assertHostPort(config);
53 return config;
54}
55exports.givenHttpServerConfig = givenHttpServerConfig;
56function setupTlsConfig(config) {
57 if ('key' in config && 'cert' in config)
58 return;
59 if ('pfx' in config)
60 return;
61 Object.assign(config, DUMMY_TLS_CONFIG);
62}
63/**
64 * Type guard to check if the parameter is `HttpsOptions`
65 */
66function isHttpsConfig(config) {
67 return (config === null || config === void 0 ? void 0 : config.protocol) === 'https';
68}
69/**
70 * Type guard to assert the parameter is `HttpOptions`
71 * @param config - Http config
72 */
73function assertHttpConfig(config) {
74 (0, assert_1.default)((config === null || config === void 0 ? void 0 : config.protocol) == null || (config === null || config === void 0 ? void 0 : config.protocol) === 'http');
75}
76//# sourceMappingURL=http-server-config.js.map
\No newline at end of file