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