UNPKG

1.99 kBPlain TextView Raw
1// Copyright IBM Corp. 2018,2019. All Rights Reserved.
2// Node module: @loopback/testlab
3// This file is licensed under the MIT License.
4// License text available at https://opensource.org/licenses/MIT
5
6import {readFileSync} from 'fs';
7import {ServerOptions as HttpsServerOptions} from 'https';
8import {ListenOptions} from 'net';
9import path from 'path';
10
11const FIXTURES = path.resolve(__dirname, '../fixtures');
12const DUMMY_TLS_CONFIG = {
13 key: readFileSync(path.join(FIXTURES, 'key.pem')),
14 cert: readFileSync(path.join(FIXTURES, 'cert.pem')),
15};
16
17export interface HttpOptions extends ListenOptions {
18 protocol?: 'http';
19}
20
21export interface HttpsOptions extends ListenOptions, HttpsServerOptions {
22 protocol: 'https';
23}
24
25export type HostPort = {
26 host: string;
27 port: number;
28};
29
30/**
31 * Create an HTTP-server configuration that works well in test environments.
32 * - Ask the operating system to assign a free (ephemeral) port.
33 * - Use IPv4 localhost `127.0.0.1` to avoid known IPv6 issues in Docker-based
34 * environments like Travis-CI.
35 * - Provide default TLS key & cert when `protocol` is set to `https`.
36 *
37 * @param customConfig - Additional configuration options to apply.
38 */
39export function givenHttpServerConfig<T extends HttpOptions | HttpsOptions>(
40 customConfig?: T,
41): HostPort & T {
42 const defaults = {
43 host: '127.0.0.1',
44 port: 0,
45 protocol: undefined,
46 };
47 const config = Object.assign({}, defaults, customConfig);
48 if (config.host === undefined) config.host = defaults.host;
49 if (config.port === undefined) config.port = defaults.port;
50 if (isHttpsConfig(config)) {
51 setupTlsConfig(config);
52 }
53 return config;
54}
55
56function setupTlsConfig(config: HttpsServerOptions) {
57 if ('key' in config && 'cert' in config) return;
58 if ('pfx' in config) return;
59 Object.assign(config, DUMMY_TLS_CONFIG);
60}
61
62function isHttpsConfig(
63 config: HttpOptions | HttpsOptions,
64): config is HttpsOptions {
65 return config && config.protocol === 'https';
66}