better code: support for http post

Massimo Melina committed Jul 18, 2023 at 22:59 UTC 7cd26833bd6309d155b7b541ff17a5415d7f213c
1 file changed +9 -3
src/util-http.ts
+9 -3
@@ -5,7 +5,7 @@ import { IncomingMessage } from 'node:http'
5 import https from 'node:https'
6 import { HTTP_TEMPORARY_REDIRECT } from './const'
7
8 -export function httpsString(url: string, options:RequestOptions={}): Promise<IncomingMessage & { ok: boolean, body: string }> {
8 +export function httpsString(url: string, options?: XRequestOptions): Promise<IncomingMessage & { ok: boolean, body: string }> {
9 return httpsStream(url, options).then(res =>
10 new Promise(resolve => {
11 let buf = ''
@@ -18,8 +18,11 @@ export function httpsString(url: string, options:RequestOptions={}): Promise<Inc
18 )
19 }
20
21 -export function httpsStream(url: string, options:RequestOptions={}): Promise<IncomingMessage> {
21 +export interface XRequestOptions extends RequestOptions { body?: string | Buffer }
22 +export function httpsStream(url: string, { body, ...options }:XRequestOptions ={}): Promise<IncomingMessage> {
23 return new Promise((resolve, reject) => {
24 + if (body)
25 + options.method ||= 'POST'
26 const req = https.request(url, options, res => {
27 if (!res.statusCode || res.statusCode >= 400)
28 return reject(new Error(String(res.statusCode), { cause: res }))
@@ -28,7 +31,10 @@ export function httpsStream(url: string, options:RequestOptions={}): Promise<Inc
31 resolve(res)
32 }).on('error', e => {
33 reject((req as any).res || e)
31 - }).end()
34 + })
35 + if (body)
36 + req.write(body)
37 + req.end()
38 })
39 }
40