Minimal JSON fetch over https/http.
(url: string, opts?: { method?: string; body?: string; headers?: Record<string, string> })
| 27 | |
| 28 | /** Minimal JSON fetch over https/http. */ |
| 29 | function fetchJSON<T>(url: string, opts?: { method?: string; body?: string; headers?: Record<string, string> }): Promise<T> { |
| 30 | return new Promise((resolve, reject) => { |
| 31 | const parsed = new URL(url); |
| 32 | const isHttps = parsed.protocol === "https:"; |
| 33 | const req = (isHttps ? nodeRequest : nodeHttpRequest)( |
| 34 | { |
| 35 | hostname: parsed.hostname, |
| 36 | port: parsed.port || (isHttps ? 443 : 80), |
| 37 | path: parsed.pathname + parsed.search, |
| 38 | method: opts?.method ?? "GET", |
| 39 | headers: { |
| 40 | "Content-Type": "application/x-www-form-urlencoded", |
| 41 | Accept: "application/json", |
| 42 | ...(opts?.headers ?? {}), |
| 43 | }, |
| 44 | }, |
| 45 | (res) => { |
| 46 | const chunks: Buffer[] = []; |
| 47 | res.on("data", (c: Buffer) => chunks.push(c)); |
| 48 | res.on("end", () => { |
| 49 | try { |
| 50 | resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")) as T); |
| 51 | } catch (e) { |
| 52 | reject(e); |
| 53 | } |
| 54 | }); |
| 55 | }, |
| 56 | ); |
| 57 | req.on("error", reject); |
| 58 | if (opts?.body) req.write(opts.body); |
| 59 | req.end(); |
| 60 | }); |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * OAuth2 / OIDC authentication adapter. |