1 | var _ = require('lodash');
|
2 | var url = require('url');
|
3 | var logger = require('./logger').getInstance();
|
4 |
|
5 | module.exports = {
|
6 | createConfig: createConfig
|
7 | };
|
8 |
|
9 | function createConfig(context, opts) {
|
10 |
|
11 | var config = {
|
12 | context: undefined,
|
13 | options: {}
|
14 | };
|
15 |
|
16 |
|
17 | if (isContextless(context, opts)) {
|
18 | config.context = '/';
|
19 | config.options = _.assign(config.options, context);
|
20 | }
|
21 |
|
22 |
|
23 | else if (isStringShortHand(context)) {
|
24 | var oUrl = url.parse(context);
|
25 | var target = [oUrl.protocol, '//', oUrl.host].join('');
|
26 |
|
27 | config.context = oUrl.pathname || '/';
|
28 | config.options = _.assign(config.options, {target: target}, opts);
|
29 |
|
30 | if (oUrl.protocol === 'ws:' || oUrl.protocol === 'wss:') {
|
31 | config.options.ws = true;
|
32 | }
|
33 |
|
34 | } else {
|
35 | config.context = context;
|
36 | config.options = _.assign(config.options, opts);
|
37 | }
|
38 |
|
39 | configureLogger(config.options);
|
40 |
|
41 | if (!config.options.target) {
|
42 | throw new Error('[HPM] Missing "target" option. Example: {target: "http://www.example.org"}');
|
43 | }
|
44 |
|
45 |
|
46 | config.options = mapLegacyProxyHostOption(config.options);
|
47 |
|
48 | return config;
|
49 | }
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 | function isStringShortHand(context) {
|
63 | if (_.isString(context)) {
|
64 | return (url.parse(context).host) ? true : false;
|
65 | }
|
66 | }
|
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 | function isContextless(context, opts) {
|
80 | return (_.isPlainObject(context) && _.isEmpty(opts));
|
81 | }
|
82 |
|
83 | function mapLegacyProxyHostOption(options) {
|
84 |
|
85 | if (options.proxyHost) {
|
86 | logger.warn('*************************************');
|
87 | logger.warn('[HPM] Deprecated "option.proxyHost"');
|
88 | logger.warn(' Use "option.changeOrigin" or "option.headers.host" instead');
|
89 | logger.warn(' "option.proxyHost" will be removed in future release.');
|
90 | logger.warn('*************************************');
|
91 |
|
92 | options.headers = options.headers || {};
|
93 | options.headers.host = options.proxyHost;
|
94 | }
|
95 |
|
96 | return options;
|
97 | }
|
98 |
|
99 | function configureLogger(options) {
|
100 | if (options.logLevel) {
|
101 | logger.setLevel(options.logLevel);
|
102 | }
|
103 |
|
104 | if (options.logProvider) {
|
105 | logger.setProvider(options.logProvider);
|
106 | }
|
107 | }
|