|
| 1 | +import { request as http, RequestOptions, ClientRequest, IncomingMessage } from "http"; |
| 2 | +import { request as https } from "https"; |
| 3 | +import { URL } from "url"; |
| 4 | +import { HttpRequester } from "./base"; |
| 5 | + |
| 6 | +export const httpRequester: HttpRequester = async (option) => { |
| 7 | + let headers: Record<string, string> = { ...option.headers }; |
| 8 | + let requestOption: RequestOptions = { |
| 9 | + method: option.method, |
| 10 | + headers, |
| 11 | + agent: option.userAgent, |
| 12 | + } |
| 13 | + let url = new URL(option.url); |
| 14 | + |
| 15 | + let body: Buffer | undefined; |
| 16 | + if (option.body) { |
| 17 | + headers["Content-Type"] = "application/json"; |
| 18 | + body = Buffer.from(JSON.stringify(option.body), "utf-8"); |
| 19 | + } |
| 20 | + return new Promise<{ |
| 21 | + body: string; |
| 22 | + statusMessage: string; |
| 23 | + statusCode: number; |
| 24 | + }>((resolve, reject) => { |
| 25 | + function handleMessage(message: IncomingMessage) { |
| 26 | + let buffers = [] as Buffer[]; |
| 27 | + message.on("data", (buf) => { buffers.push(buf); }); |
| 28 | + message.on("end", () => { |
| 29 | + resolve({ |
| 30 | + body: Buffer.concat(buffers).toString("utf-8"), |
| 31 | + statusCode: message.statusCode || -1, |
| 32 | + statusMessage: message.statusMessage || "", |
| 33 | + }); |
| 34 | + }); |
| 35 | + message.on("error", reject); |
| 36 | + } |
| 37 | + let req: ClientRequest; |
| 38 | + if (url.protocol === "https:") { |
| 39 | + req = https(url, requestOption, handleMessage); |
| 40 | + } else if (url.protocol === "http:") { |
| 41 | + req = http(url, requestOption, handleMessage); |
| 42 | + } else { |
| 43 | + reject(new Error(`Unsupported protocol ${url.protocol}`)); |
| 44 | + return; |
| 45 | + } |
| 46 | + req.on("error", reject); |
| 47 | + if (body) { |
| 48 | + req.write(body); |
| 49 | + } |
| 50 | + req.end(); |
| 51 | + }); |
| 52 | +} |
0 commit comments