requestService.ts 2.1 KB
Newer Older
J
Joao Moreno 已提交
1 2 3 4 5 6 7 8
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

import { TPromise } from 'vs/base/common/winjs.base';
import { IDisposable } from 'vs/base/common/lifecycle';
J
Joao Moreno 已提交
9
import { assign } from 'vs/base/common/objects';
J
Joao Moreno 已提交
10 11
import { IRequestOptions, IRequestContext, request } from 'vs/base/node/request';
import { getProxyAgent } from 'vs/base/node/proxy';
J
Joao Moreno 已提交
12
import { IRequestService, IHTTPConfiguration } from 'vs/platform/request/common/request';
J
Joao Moreno 已提交
13 14 15 16 17 18
import { IConfigurationService, IConfigurationServiceEvent } from 'vs/platform/configuration/common/configuration';

/**
 * This service exposes the `request` API, while using the global
 * or configured proxy settings.
 */
J
Joao Moreno 已提交
19
export class RequestService implements IRequestService {
J
Joao Moreno 已提交
20 21 22 23 24

	_serviceBrand: any;

	private proxyUrl: string;
	private strictSSL: boolean;
J
Joao Moreno 已提交
25
	private authorization: string;
J
Joao Moreno 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
	private disposables: IDisposable[] = [];

	constructor(
		@IConfigurationService configurationService: IConfigurationService
	) {
		this.configure(configurationService.getConfiguration<IHTTPConfiguration>());
		configurationService.onDidUpdateConfiguration(this.onDidUpdateConfiguration, this, this.disposables);
	}

	private onDidUpdateConfiguration(e: IConfigurationServiceEvent) {
		this.configure(e.config);
	}

	private configure(config: IHTTPConfiguration) {
		this.proxyUrl = config.http && config.http.proxy;
		this.strictSSL = config.http && config.http.proxyStrictSSL;
J
Joao Moreno 已提交
42
		this.authorization = config.http && config.http.proxyAuthorization;
J
Joao Moreno 已提交
43 44 45 46 47 48 49 50
	}

	request(options: IRequestOptions): TPromise<IRequestContext> {
		if (!options.agent) {
			const { proxyUrl, strictSSL } = this;
			options.agent = getProxyAgent(options.url, { proxyUrl, strictSSL });
		}

J
Joao Moreno 已提交
51 52 53 54
		if (this.authorization) {
			options.headers = assign(options.headers || {}, { 'Proxy-Authorization': this.authorization });
		}

J
Joao Moreno 已提交
55 56 57
		return request(options);
	}
}