|
| 1 | +import { Adapter, RequestConfig } from './types/adapters'; |
| 2 | +import { HttpError } from './HttpError'; |
| 3 | + |
| 4 | +export class FetchAdapter implements Adapter { |
| 5 | + protected readonly baseURL: string; |
| 6 | + protected readonly defaultHeaders: Record<string, string> = {}; |
| 7 | + |
| 8 | + constructor(baseURL: string) { |
| 9 | + this.baseURL = baseURL; |
| 10 | + } |
| 11 | + |
| 12 | + setHeader(header: string, value: string): void { |
| 13 | + this.defaultHeaders[header] = value; |
| 14 | + } |
| 15 | + |
| 16 | + async get<T>(url: string, config?: RequestConfig): Promise<T> { |
| 17 | + return this.request<T>('GET', url, undefined, config); |
| 18 | + } |
| 19 | + |
| 20 | + async post<T>(url: string, body: unknown, config?: RequestConfig): Promise<T> { |
| 21 | + return this.request<T>('POST', url, body, config); |
| 22 | + } |
| 23 | + |
| 24 | + async put<T>(url: string, body: unknown, config?: RequestConfig): Promise<T> { |
| 25 | + return this.request<T>('PUT', url, body, config); |
| 26 | + } |
| 27 | + |
| 28 | + async delete<T>(url: string, config?: RequestConfig): Promise<T> { |
| 29 | + return this.request<T>('DELETE', url, undefined, config); |
| 30 | + } |
| 31 | + |
| 32 | + protected async request<T>(method: string, path: string, body: unknown, config?: RequestConfig): Promise<T> { |
| 33 | + let fullURL = this.baseURL + path; |
| 34 | + |
| 35 | + if (config?.params) { |
| 36 | + const params = new URLSearchParams(); |
| 37 | + for (const [key, value] of Object.entries(config.params)) { |
| 38 | + if (value !== undefined) { |
| 39 | + params.set(key, String(value)); |
| 40 | + } |
| 41 | + } |
| 42 | + const qs = params.toString(); |
| 43 | + if (qs) { |
| 44 | + fullURL += '?' + qs; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + const headers: Record<string, string> = { |
| 49 | + 'content-type': 'application/json', |
| 50 | + ...this.defaultHeaders, |
| 51 | + ...config?.headers |
| 52 | + }; |
| 53 | + |
| 54 | + if (config?.auth) { |
| 55 | + const encoded = Buffer.from(`${config.auth.username}:${config.auth.password}`).toString('base64'); |
| 56 | + headers['authorization'] = `Basic ${encoded}`; |
| 57 | + } |
| 58 | + |
| 59 | + const response = await fetch(fullURL, { |
| 60 | + method, |
| 61 | + headers, |
| 62 | + body: body !== undefined ? JSON.stringify(body) : undefined |
| 63 | + }); |
| 64 | + |
| 65 | + if (!response.ok) { |
| 66 | + let data: unknown; |
| 67 | + try { |
| 68 | + data = await response.json(); |
| 69 | + } catch { |
| 70 | + data = await response.text(); |
| 71 | + } |
| 72 | + throw new HttpError(response.status, response.statusText, data); |
| 73 | + } |
| 74 | + |
| 75 | + return (await response.json()) as T; |
| 76 | + } |
| 77 | +} |
0 commit comments