Skip to content

Commit

Permalink
🏭 Add partial typing for the wretch options
Browse files Browse the repository at this point in the history
Solves #253 and #251
  • Loading branch information
elbywan committed Oct 29, 2024
1 parent db86a5f commit e778f88
Show file tree
Hide file tree
Showing 7 changed files with 20 additions and 22 deletions.
4 changes: 2 additions & 2 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { mix } from "./utils.js"
import type { Config, ErrorType } from "./types.js"
import type { Config, ErrorType, WretchOptions } from "./types.js"

declare const global

Expand Down Expand Up @@ -42,7 +42,7 @@ const config: Config = {
* @param options Default options
* @param replace If true, completely replaces the existing options instead of mixing in
*/
export function setOptions(options: object, replace = false) {
export function setOptions(options: WretchOptions, replace = false) {
config.options = replace ? options : mix(config.options, options)
}

Expand Down
4 changes: 2 additions & 2 deletions src/index.cts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import factory from "./index.js";
import factory from "./index.js"

module.exports = factory.default;
module.exports = factory.default
7 changes: 2 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { setOptions, setErrorType, setPolyfills } from "./config.js"
import { core } from "./core.js"
import { WretchError } from "./resolver.js"
import type { Wretch } from "./types.js"
import type { Wretch, WretchOptions } from "./types.js"

export type {
Wretch,
Expand Down Expand Up @@ -33,16 +33,13 @@ export type {
* @param _options The base fetch options
* @returns A fresh wretch instance
*/
function factory(_url = "", _options = {}): Wretch {
function factory(_url = "", _options: WretchOptions = {}): Wretch {
return { ...core, _url, _options }
}

factory["default"] = factory
/** {@inheritDoc setOptions} */
factory.options = setOptions
/** {@inheritDoc setErrorType} */
factory.errorType = setErrorType
/** {@inheritDoc setPolyfills} */
factory.polyfills = setPolyfills
factory.WretchError = WretchError

Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -761,7 +761,7 @@ export type Config = {
/**
* Fetch Request options with additional properties.
*/
export type WretchOptions = Record<string, any>
export type WretchOptions = Record<string, any> & RequestInit
/**
* An Error enhanced with status, text and body.
*/
Expand Down
5 changes: 3 additions & 2 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { CONTENT_TYPE_HEADER } from "./constants.js"

export function extractContentType(headers: Record<string, string> = {}): string | undefined {
return Object.entries(headers).find(([k]) =>
export function extractContentType(headers: HeadersInit = {}): string | undefined {
const normalizedHeaders = headers instanceof Array ? Object.fromEntries(headers) : headers
return Object.entries(normalizedHeaders).find(([k]) =>
k.toLowerCase() === CONTENT_TYPE_HEADER.toLowerCase()
)?.[1]
}
Expand Down
8 changes: 4 additions & 4 deletions test/deno/wretch_test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import {
assertEquals,
fail
} from "https://deno.land/[email protected]/testing/asserts.ts"
} from "jsr:@std/assert"
import {
beforeAll,
describe,
it,
} from "https://deno.land/[email protected]/testing/bdd.ts"
} from "jsr:@std/testing/bdd"

import wretchFn from "../../dist/bundle/wretch.min.mjs"
import BasicAuthAddon from "../../dist/bundle/addons/basicAuth.min.mjs"
Expand Down Expand Up @@ -117,7 +117,7 @@ describe("Wretch", function () {
}
// Ensure that the charset is preserved.
const headerWithCharset = "application/json; charset=utf-16"
assertEquals((wretch()).content(headerWithCharset).json({})._options.headers["Content-Type"], headerWithCharset)
assertEquals((wretch()).content(headerWithCharset).json({})._options.headers?.["Content-Type" as keyof HeadersInit], headerWithCharset)
})

it("should perform an url encoded form data round trip", async function () {
Expand Down Expand Up @@ -395,7 +395,7 @@ describe("Wretch", function () {
await wretch(_URL + "/basicauth")
.get()
.res(_ => fail("Authenticated route should not respond without credentials."))
} catch (e) {
} catch (e: any) {
assertEquals(e.status, 401)
}
})
Expand Down
12 changes: 6 additions & 6 deletions test/node/middlewares/retry.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export default describe("Retry Middleware", () => {
true
)
.options({ a: 1 })
await expect(w.get("/retry").res()).rejects.toThrowError(
await expect(w.get("/retry").res()).rejects.toThrow(
"Number of attempts exceeded."
)
expect(counter).toEqual(10)
Expand All @@ -114,17 +114,17 @@ export default describe("Retry Middleware", () => {
delayTimer: 1,
onRetry() {
counter++
return { url: `/${counter}`, options: { method: counter } }
return { url: `/${counter}`, options: { method: `${counter}` } }
},
}),
],
true
)
await expect(w.options({ a: 0 }).get("/0").res()).rejects.toThrowError(
await expect(w.options({ a: 0 }).get("/0").res()).rejects.toThrow(
"Number of attempts exceeded."
)
logs.forEach((log, index) => {
expect(log).toMatchObject([`/${index}`, index === 0 ? "GET" : index])
expect(log).toMatchObject([`/${index}`, index === 0 ? "GET" : `${index}`])
})
})

Expand Down Expand Up @@ -161,10 +161,10 @@ export default describe("Retry Middleware", () => {
true
)

await expect(wThrow.get("/retry").res()).rejects.toThrowError(
await expect(wThrow.get("/retry").res()).rejects.toThrow(
"Network Error"
)
await expect(wRetry.get("/retry").res()).rejects.toThrowError(
await expect(wRetry.get("/retry").res()).rejects.toThrow(
"Network Error"
)
expect(counter).toBe(10)
Expand Down

0 comments on commit e778f88

Please sign in to comment.