Last active
October 17, 2021 06:26
-
-
Save vagnercardosoweb/ec683a040c24f10833932b189b2c4c0d to your computer and use it in GitHub Desktop.
request https default node
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import https, { RequestOptions } from 'https'; | |
| export interface HttpRequest extends RequestOptions { | |
| url: string; | |
| body?: string; | |
| method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS'; | |
| } | |
| interface Response<T = Buffer | any> { | |
| body: T; | |
| statusCode: number; | |
| } | |
| export default async function httpRequest<T = Buffer | any>( | |
| options: HttpRequest, | |
| ): Promise<Response<T>> { | |
| const { url, body, ...rest } = options; | |
| if (!rest.method) { | |
| rest.method = 'GET'; | |
| } | |
| const response = await new Promise<Response>((resolve, reject) => { | |
| const chunks: any[] = []; | |
| const request = https.request(url, rest, httpResponse => { | |
| httpResponse.on('error', reject); | |
| httpResponse.on('data', chunk => chunks.push(chunk)); | |
| httpResponse.on('end', () => { | |
| let buffer = Buffer.concat(chunks); | |
| try { | |
| buffer = JSON.parse(buffer.toString()); | |
| } catch { | |
| // | |
| } | |
| resolve({ | |
| body: buffer, | |
| statusCode: httpResponse.statusCode ?? 500, | |
| }); | |
| }); | |
| }); | |
| request.on('error', reject); | |
| if (['POST', 'PUT', 'PATCH'].includes(rest.method) && body) { | |
| request.write(body); | |
| } | |
| request.end(); | |
| }); | |
| if (response.statusCode >= 400) { | |
| throw new Error(`Unable to make request in ([${rest.method}] ${url}).`); | |
| } | |
| return response; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment