(config: Config = {})
| 18 | } |
| 19 | |
| 20 | export const createClient = (config: Config = {}): Client => { |
| 21 | let _config = mergeConfigs(createConfig(), config) |
| 22 | |
| 23 | const getConfig = (): Config => ({ ..._config }) |
| 24 | |
| 25 | const setConfig = (config: Config): Config => { |
| 26 | _config = mergeConfigs(_config, config) |
| 27 | return getConfig() |
| 28 | } |
| 29 | |
| 30 | const interceptors = createInterceptors<Request, Response, unknown, ResolvedRequestOptions>() |
| 31 | |
| 32 | const beforeRequest = async (options: RequestOptions) => { |
| 33 | const opts = { |
| 34 | ..._config, |
| 35 | ...options, |
| 36 | fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, |
| 37 | headers: mergeHeaders(_config.headers, options.headers), |
| 38 | serializedBody: undefined, |
| 39 | } |
| 40 | |
| 41 | if (opts.security) { |
| 42 | await setAuthParams({ |
| 43 | ...opts, |
| 44 | security: opts.security, |
| 45 | }) |
| 46 | } |
| 47 | |
| 48 | if (opts.requestValidator) { |
| 49 | await opts.requestValidator(opts) |
| 50 | } |
| 51 | |
| 52 | if (opts.body && opts.bodySerializer) { |
| 53 | opts.serializedBody = opts.bodySerializer(opts.body) |
| 54 | } |
| 55 | |
| 56 | // remove Content-Type header if body is empty to avoid sending invalid requests |
| 57 | if (opts.serializedBody === undefined || opts.serializedBody === "") { |
| 58 | opts.headers.delete("Content-Type") |
| 59 | } |
| 60 | |
| 61 | const url = buildUrl(opts) |
| 62 | |
| 63 | return { opts, url } |
| 64 | } |
| 65 | |
| 66 | const request: Client["request"] = async (options) => { |
| 67 | // @ts-expect-error |
| 68 | const { opts, url } = await beforeRequest(options) |
| 69 | const requestInit: ReqInit = { |
| 70 | redirect: "follow", |
| 71 | ...opts, |
| 72 | body: opts.serializedBody, |
| 73 | } |
| 74 | |
| 75 | let request = new Request(url, requestInit) |
| 76 | |
| 77 | for (const fn of interceptors.request._fns) { |
no test coverage detected