Skip to content

Commit

Permalink
add timeout to HTTP request
Browse files Browse the repository at this point in the history
  • Loading branch information
bitrinjani committed Nov 27, 2017
1 parent b1d3b50 commit ab544c1
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/WebClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,28 @@ import fetch, { RequestInit as FetchRequestInit } from 'node-fetch';
import { getLogger } from './logger';

export default class WebClient {
static fetchTimeout = 5000;
private log = getLogger('WebClient');

constructor(public baseUrl: string) {
this.baseUrl = baseUrl;
}

async fetch<T>(path: string, init: FetchRequestInit = {}, verbose: boolean = true): Promise<T> {
async fetch<T>(
path: string,
init: FetchRequestInit = { timeout: WebClient.fetchTimeout },
verbose: boolean = true): Promise<T> {
const url = this.baseUrl + path;
this.log.debug(`Sending HTTP request... URL: ${url} Request: ${JSON.stringify(init)}`);
const res = await fetch(url, init);
let logText = `Response from ${res.url}. ` +
`Status Code: ${res.status} (${res.statusText}) `;
this.log.debug(logText);
this.log.debug(logText);
const content = await res.text();
if (!res.ok) {
if (!res.ok) {
logText += `Content: ${content}`;
throw new Error(`HTTP request failed. ${logText}`);
}
}
if (!content) {
return {} as T;
}
Expand Down

0 comments on commit ab544c1

Please sign in to comment.