How to use the typed-rest-client/HttpClient.HttpClient function in typed-rest-client

To help you get started, we’ve selected a few typed-rest-client examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github actions / cache / src / cacheHttpClient.ts View on Github external
export async function downloadCache(
    cacheEntry: ArtifactCacheEntry,
    archivePath: string
): Promise {
    const stream = fs.createWriteStream(archivePath);
    const httpClient = new HttpClient("actions/cache");
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    const downloadResponse = await httpClient.get(cacheEntry.archiveLocation!);
    await pipeResponseToStream(downloadResponse, stream);
}
github microsoft / typed-rest-client / test / units / httptests.ts View on Github external
it('doesnt retry non-retryable return codes', async() => {
        _http = new httpm.HttpClient('typed-test-client-tests', null, {allowRetries: true, maxRetries: 3});

        let numTries = 0;
        nock('http://microsoft.com')
            .options('/')
            .times(1)
            .reply(501, function(uri, requestBody) {
                numTries += 1;
            });
        let res: httpm.HttpClientResponse = await _http.options('http://microsoft.com');
        assert(numTries == 1, "client should not retry on failure");
        assert(res.message.statusCode == 501, "status code should be 501");
    });
});
github microsoft / typed-rest-client / test / httptests.ts View on Github external
before(() => {
        _http = new httpm.HttpClient('typed-test-client-tests', [], { keepAlive: true });
    });
github microsoft / typed-rest-client / test / units / httptests.ts View on Github external
before(() => {
        _http = new httpm.HttpClient('typed-test-client-tests', [], { keepAlive: true });
    });
github microsoft / azure-pipelines-tasks / Tasks / AzureMonitorAlertsV0 / Tests / L0AccessTokenFetchSuccess.ts View on Github external
import * as querystring from "querystring";
import * as assert from "assert";
import { HttpClient } from "typed-rest-client/HttpClient";
import { AuthorizationClient } from "../authorizationclient";

var nock = require("nock");

let endpoint = {
	url: "http://example.com/",
	tenantID: "tenantId",
	servicePrincipalKey: "spKey",
	servicePrincipalClientID: "spId",
	activeDirectoryResourceId: "http://example.com/"
};

let httpClient = new HttpClient("TEST_AGENT");

async function testGetBearerToken1() {
	try {
		let authorizationclient = new AuthorizationClient(endpoint, httpClient);

		mockRequest("accessToken", `${Math.floor(new Date().getTime()/1000) + 3600}`);
		let token1 = await authorizationclient.getBearerToken();
		let token2 = await authorizationclient.getBearerToken();

		assert(token1 === "accessToken", "new access token should have been returned");
		assert(token2 === "accessToken", "stored access token should have been returned");
	}
	catch (error) {
		console.error(error);
	}
}
github mauve / vscode-terraform / src / commands / installLanguageServer.ts View on Github external
const releaseDetails =
        availableReleses.filter((v) => v.id.toString() === releaseId)[0];

    let platform = process.platform.toString();
    platform = platform === 'win32' ? 'windows' : platform;
    const downloadUrl = this.getDownloadUrl(releaseDetails, platform);

    if (downloadUrl === 'NotFound') {
      vscode.window.showErrorMessage(
          `Failed to install, releases for the Lanugage server didn't contain a release for your platform: ${
              platform}`);
      return;
    }

    const client = new HttpClient('clientTest');
    const response = await client.get(downloadUrl);
    const file: NodeJS.WritableStream = fs.createWriteStream(downloadedZipFile);

    if (response.message.statusCode !== 200) {
      const err: Error =
          new Error(`Unexpected HTTP response: ${response.message.statusCode}`);
      err['httpStatusCode'] = response.message.statusCode;
      vscode.window.showErrorMessage(
          `Downloading Terraform language server failed with ${err}`);
      return;
    }

    return new Promise((resolve, reject) => {
      file.on('error', (err) => reject(err));
      const stream = response.message.pipe(file);
      stream.on('close', () => {
github microsoft / azure-pipelines-tasks / Tasks / AzureMonitorAlertsV0 / azurermalertrulesrestclient.ts View on Github external
constructor(endpoint) {
		this._endpoint = endpoint;

		let proxyUrl: string = tl.getVariable("agent.proxyurl"); 
		let requestOptions: IHttpRequestOptions = !!proxyUrl ? { 
			proxy: { 
				proxyUrl: proxyUrl, 
				proxyUsername: tl.getVariable("agent.proxyusername"), 
				proxyPassword: tl.getVariable("agent.proxypassword"), 
				proxyBypassHosts: tl.getVariable("agent.proxybypasslist") ? JSON.parse(tl.getVariable("agent.proxybypasslist")) : null 
			}
		} : null; 

		this._httpClient = new HttpClient(tl.getVariable("AZURE_HTTP_USER_AGENT"), null, requestOptions);
		this._restClient = new RestClient(tl.getVariable("AZURE_HTTP_USER_AGENT"), null, null, requestOptions);
		this._authorizationClient = new AuthorizationClient(endpoint, this._httpClient);
	}
github actions / toolkit / packages / tool-cache / src / tool-cache.ts View on Github external
return new Promise(async (resolve, reject) => {
    try {
      const http = new httpm.HttpClient(userAgent, [], {
        allowRetries: true,
        maxRetries: 3
      })
      dest = dest || path.join(tempDirectory, uuidV4())
      await io.mkdirP(path.dirname(dest))
      core.debug(`Downloading ${url}`)
      core.debug(`Downloading ${dest}`)

      if (fs.existsSync(dest)) {
        throw new Error(`Destination file path ${dest} already exists`)
      }

      const response: httpm.HttpClientResponse = await http.get(url)

      if (response.message.statusCode !== 200) {
        const err = new HTTPError(response.message.statusCode)
github stryker-mutator / stryker / packages / core / src / reporters / dashboard-reporter / index.ts View on Github external
export function dashboardReporterFactory(injector: Injector): DashboardReporter {
  return injector
    .provideValue(dashboardReporterTokens.httpClient, new HttpClient('stryker-dashboard-reporter'))
    .provideClass(dashboardReporterTokens.dashboardReporterClient, DashboardReporterClient)
    .provideFactory(dashboardReporterTokens.ciProvider, determineCIProvider)
    .injectClass(DashboardReporter);
}
dashboardReporterFactory.inject = tokens(commonTokens.injector);
github expo / expo-github-action / node_modules / @actions / tool-cache / lib / tool-cache.js View on Github external
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
            try {
                const http = new httpm.HttpClient(userAgent, [], {
                    allowRetries: true,
                    maxRetries: 3
                });
                const destPath = path.join(tempDirectory, uuidV4());
                yield io.mkdirP(tempDirectory);
                core.debug(`Downloading ${url}`);
                core.debug(`Downloading ${destPath}`);
                if (fs.existsSync(destPath)) {
                    throw new Error(`Destination file path ${destPath} already exists`);
                }
                const response = yield http.get(url);
                if (response.message.statusCode !== 200) {
                    const err = new HTTPError(response.message.statusCode);
                    core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
                    throw err;
                }