Skip to content

Commit b0316f1

Browse files
committed
🎨 Golf bytes
1 parent bdb8134 commit b0316f1

File tree

9 files changed

+48
-59
lines changed

9 files changed

+48
-59
lines changed

src/addons/progress.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,7 @@ function toStream<T extends Request | Response>(requestOrResponse: T, callback:
8787
if (total < loaded) {
8888
total = loaded
8989
}
90-
if (callback) {
91-
callback?.(loaded, total)
92-
}
90+
callback?.(loaded, total)
9391
controller.enqueue(chunk)
9492
}
9593
})

src/addons/queryString.ts

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
import type { Wretch, WretchAddon } from "../types.js"
22

3-
function stringify(value?: string | null): string | null {
4-
return typeof value !== "undefined" ? value : ""
5-
}
6-
73
/**
84
* Options for the query method.
95
*/
@@ -28,11 +24,11 @@ const appendQueryParams = (url: string, qp: object | string, replace: boolean, o
2824
for (const key in qp) {
2925
const value = qp[key]
3026
if (omitUndefinedOrNullValues && (value === null || value === undefined)) continue
31-
if (qp[key] instanceof Array) {
27+
if (Array.isArray(value)) {
3228
for (const val of value)
33-
usp.append(key, stringify(val))
29+
usp.append(key, val ?? "")
3430
} else {
35-
usp.append(key, stringify(value))
31+
usp.append(key, value ?? "")
3632
}
3733
}
3834
queryString = usp.toString()

src/constants.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
11
export const JSON_MIME = "application/json"
2-
export const CONTENT_TYPE_HEADER = "Content-Type"
32
export const FETCH_ERROR = Symbol()
43
export const CATCHER_FALLBACK = Symbol()

src/core.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { mix, extractContentType, isLikelyJsonMime } from "./utils.js"
2-
import { JSON_MIME, CONTENT_TYPE_HEADER, CATCHER_FALLBACK } from "./constants.js"
2+
import { JSON_MIME, CATCHER_FALLBACK } from "./constants.js"
33
import { resolver } from "./resolver.js"
44
import type { Wretch } from "./types.js"
55

@@ -20,11 +20,11 @@ export const core: Wretch = {
2020
url(_url, replace = false) {
2121
if (replace)
2222
return { ...this, _url }
23-
const split = this._url.split("?")
23+
const idx = this._url.indexOf("?")
2424
return {
2525
...this,
26-
_url: split.length > 1 ?
27-
split[0] + _url + "?" + split[1] :
26+
_url: idx > -1 ?
27+
this._url.slice(0, idx) + _url + this._url.slice(idx) :
2828
this._url + _url
2929
}
3030
},
@@ -43,7 +43,7 @@ export const core: Wretch = {
4343
return this.headers({ Accept: headerValue })
4444
},
4545
content(headerValue) {
46-
return this.headers({ [CONTENT_TYPE_HEADER]: headerValue })
46+
return this.headers({ "Content-Type": headerValue })
4747
},
4848
auth(headerValue) {
4949
return this.headers({ Authorization: headerValue })

src/index.all.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,15 @@ import { core } from "./core.js"
22
import * as Addons from "./addons/index.js"
33
import { WretchError } from "./resolver.js"
44

5-
function factory(_url = "", _options = {}) {
6-
return { ...core, _url, _options }
5+
const factory = (_url = "", _options = {}) =>
6+
({ ...core, _url, _options })
77
.addon(Addons.abortAddon())
88
.addon(Addons.basicAuthAddon)
99
.addon(Addons.formDataAddon)
1010
.addon(Addons.formUrlAddon)
1111
.addon(Addons.perfsAddon())
1212
.addon(Addons.queryStringAddon)
1313
.addon(Addons.progressAddon())
14-
}
1514

1615
factory["default"] = factory
1716
factory.WretchError = WretchError

src/index.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,8 @@ export type {
3131
* @param _options The base fetch options
3232
* @returns A fresh wretch instance
3333
*/
34-
function factory(_url = "", _options: WretchOptions = {}): Wretch {
35-
return { ...core, _url, _options }
36-
}
34+
const factory = (_url = "", _options: WretchOptions = {}): Wretch =>
35+
({ ...core, _url, _options })
3736

3837
factory["default"] = factory
3938
factory.WretchError = WretchError

src/middleware.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,5 @@ import type { ConfiguredMiddleware, FetchLike } from "./types.js"
33
/**
44
* @private @internal
55
*/
6-
export const middlewareHelper = (middlewares: ConfiguredMiddleware[]) => (fetchFunction: FetchLike): FetchLike => {
7-
return middlewares.reduceRight((acc, curr) => curr(acc), fetchFunction) || fetchFunction
8-
}
6+
export const middlewareHelper = (middlewares: ConfiguredMiddleware[]) => (fetchFunction: FetchLike): FetchLike =>
7+
middlewares.reduceRight((acc, curr) => curr(acc), fetchFunction)

src/resolver.ts

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ export const resolver = <T, Chain, R, E>(wretch: T & Wretch<T, Chain, R, E>) =>
5252
if (!response.ok) {
5353
const err = new WretchError()
5454
err["cause"] = referenceError
55-
err.stack = err.stack + "\nCAUSE: " + referenceError.stack
55+
err.stack += "\nCAUSE: " + referenceError.stack
5656
err.response = response
5757
err.status = response.status
5858
err.url = finalUrl
@@ -77,34 +77,35 @@ export const resolver = <T, Chain, R, E>(wretch: T & Wretch<T, Chain, R, E>) =>
7777
return response
7878
})
7979
// Wraps the Promise in order to dispatch the error to a matching catcher
80-
const catchersWrapper = <T>(promise: Promise<T>): Promise<void | T> => {
81-
return promise.catch(err => {
82-
const fetchErrorFlag = Object.prototype.hasOwnProperty.call(err, FETCH_ERROR)
80+
const catchersWrapper = <T>(promise: Promise<T>): Promise<void | T> =>
81+
promise.catch(err => {
82+
const fetchErrorFlag = FETCH_ERROR in err
8383
const error = fetchErrorFlag ? err[FETCH_ERROR] : err
8484

8585
const catcher =
8686
(error?.status && catchers.get(error.status)) ||
87-
catchers.get(error?.name) || (
88-
fetchErrorFlag && catchers.has(FETCH_ERROR) && catchers.get(FETCH_ERROR)
89-
)
87+
catchers.get(error?.name) ||
88+
(fetchErrorFlag && catchers.get(FETCH_ERROR)) ||
89+
catchers.get(CATCHER_FALLBACK)
9090

9191
if (catcher)
9292
return catcher(error, wretch)
9393

94-
const catcherFallback = catchers.get(CATCHER_FALLBACK)
95-
if (catcherFallback)
96-
return catcherFallback(error, wretch)
97-
9894
throw error
9995
})
100-
}
10196
// Enforces the proper promise type when a body parsing method is called.
102-
type BodyParser = <Type>(funName: "json" | "blob" | "formData" | "arrayBuffer" | "text" | null) => <Result = void>(cb?: (type: Type) => Result) => Promise<Awaited<Result>>
103-
const bodyParser: BodyParser = funName => cb => funName ?
97+
type BodyParser =
98+
<Type>(funName: "json" | "blob" | "formData" | "arrayBuffer" | "text" | null)
99+
=> <Result = void>(cb?: (type: Type) => Result)
100+
=> Promise<Awaited<Result>>
101+
const bodyParser: BodyParser = funName => cb => {
102+
const promise = funName ?
104103
// If a callback is provided, then callback with the body result otherwise return the parsed body itself.
105-
catchersWrapper(throwingPromise.then(_ => _ && _[funName]()).then(_ => cb ? cb(_) : _)) :
104+
throwingPromise.then(_ => _?.[funName]()) :
106105
// No body parsing method - return the response
107-
catchersWrapper(throwingPromise.then(_ => cb ? cb(_ as any) : _))
106+
throwingPromise
107+
return catchersWrapper(cb ? promise.then(cb) : promise)
108+
}
108109

109110
const responseChain: WretchResponseChain<T, Chain, R, E> = {
110111
_wretchReq: wretch,

src/utils.ts

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,25 @@
1-
import { CONTENT_TYPE_HEADER } from "./constants.js"
2-
31
export function extractContentType(headers: HeadersInit = {}): string | undefined {
42
const normalizedHeaders = headers instanceof Array ? Object.fromEntries(headers) : headers
5-
return Object.entries(normalizedHeaders).find(([k]) =>
6-
k.toLowerCase() === CONTENT_TYPE_HEADER.toLowerCase()
7-
)?.[1]
3+
for (const k in normalizedHeaders) {
4+
if (k.toLowerCase() === "content-type") return normalizedHeaders[k]
5+
}
86
}
97

108
export function isLikelyJsonMime(value: string): boolean {
11-
return /^application\/.*json.*/.test(value)
9+
return /^application\/.*json/.test(value)
1210
}
1311

14-
export const mix = function (one: object, two: object, mergeArrays: boolean = false) {
15-
return Object.entries(two).reduce((acc, [key, newValue]) => {
12+
export const mix = (one: object, two: object, mergeArrays = false) => {
13+
const acc = { ...one }
14+
for (const key in two) {
15+
if (!Object.prototype.hasOwnProperty.call(two, key)) continue
1616
const value = one[key]
17-
if (Array.isArray(value) && Array.isArray(newValue)) {
18-
acc[key] = mergeArrays ? [...value, ...newValue] : newValue
19-
} else if (typeof value === "object" && typeof newValue === "object") {
20-
acc[key] = mix(value, newValue, mergeArrays)
21-
} else {
22-
acc[key] = newValue
23-
}
24-
25-
return acc
26-
}, { ...one })
17+
const newValue = two[key]
18+
acc[key] = Array.isArray(value) && Array.isArray(newValue) ?
19+
mergeArrays ? [...value, ...newValue] : newValue :
20+
typeof value === "object" && typeof newValue === "object" ?
21+
mix(value, newValue, mergeArrays) :
22+
newValue
23+
}
24+
return acc
2725
}

0 commit comments

Comments
 (0)