From d3c0f3c251e8371d78d953f32f7311a38f4a1bdb Mon Sep 17 00:00:00 2001 From: MeiMei <30769358+mei23@users.noreply.github.com> Date: Thu, 9 Apr 2020 23:42:23 +0900 Subject: Use node-fetch instead of request (#6228) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * requestをnode-fetchになど * format * fix error * t * Fix test --- src/misc/fetch.ts | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/misc/fetch.ts (limited to 'src/misc/fetch.ts') diff --git a/src/misc/fetch.ts b/src/misc/fetch.ts new file mode 100644 index 0000000000..887aae1659 --- /dev/null +++ b/src/misc/fetch.ts @@ -0,0 +1,43 @@ +import * as http from 'http'; +import * as https from 'https'; +import * as cache from 'lookup-dns-cache'; +import fetch, { HeadersInit } from 'node-fetch'; +import { HttpProxyAgent } from 'http-proxy-agent'; +import { HttpsProxyAgent } from 'https-proxy-agent'; +import config from '../config'; + +export async function getJson(url: string, accept = 'application/json, */*', timeout = 10000, headers?: HeadersInit) { + const res = await fetch(url, { + headers: Object.assign({ + 'User-Agent': config.userAgent, + Accept: accept + }, headers || {}), + timeout, + agent: u => u.protocol == 'http:' ? httpAgent : httpsAgent, + }); + + if (!res.ok) { + throw { + name: `StatusError`, + statusCode: res.status, + message: `${res.status} ${res.statusText}`, + }; + } + + return await res.json(); +} + +export const httpAgent = config.proxy + ? new HttpProxyAgent(config.proxy) + : new http.Agent({ + keepAlive: true, + keepAliveMsecs: 30 * 1000, + }); + +export const httpsAgent = config.proxy + ? new HttpsProxyAgent(config.proxy) + : new https.Agent({ + keepAlive: true, + keepAliveMsecs: 30 * 1000, + lookup: cache.lookup, + }); -- cgit v1.2.3-freya