Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add extractDataFromResponse util for better data from response #11

Merged
merged 3 commits into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/quiet-lizards-itch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"x-fetch": minor
---

feat: add extractDataFromResponse util for better data from response
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"license": "MIT",
"packageManager": "[email protected]",
"engines": {
"node": ">=4.0.0"
"node": ">=14.0.0"
},
"main": "./lib/index.cjs",
"module": "./lib/index.js",
Expand All @@ -24,7 +24,7 @@
"!**/*.tsbuildinfo"
],
"scripts": {
"build": "yarn test && concurrently 'yarn:build:*'",
"build": "yarn test && concurrently -r 'yarn:build:*'",
"build:r": "r -f cjs",
"build:tsc": "tsc -p src",
"dev": "vitest",
Expand Down
71 changes: 19 additions & 52 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,20 @@
import type { URLSearchParametersOptions, ValueOf } from './types.js'
import { CONTENT_TYPE, isPlainObject, normalizeUrl } from './utils.js'

export type * from './types.js'
import {
ApiMethod,
FetchApiOptions,
InterceptorRequest,
type ApiInterceptor,
type FetchApiBaseOptions,
} from './types.js'
import {
CONTENT_TYPE,
extractDataFromResponse,
isPlainObject,
normalizeUrl,
} from './utils.js'

export * from './types.js'
export * from './utils.js'

export const ApiMethod = {
GET: 'GET',
POST: 'POST',
PATCH: 'PATCH',
PUT: 'PUT',
DELETE: 'DELETE',
} as const

export type ApiMethod = ValueOf<typeof ApiMethod>

export interface FetchApiBaseOptions
extends Omit<RequestInit, 'body' | 'method'> {
method?: ApiMethod
body?: BodyInit | object
query?: URLSearchParametersOptions
json?: boolean
}

export interface FetchApiOptions extends FetchApiBaseOptions {
type?: 'arrayBuffer' | 'blob' | 'json' | 'text' | null
}

export interface InterceptorRequest extends FetchApiOptions {
url: string
}

export type ApiInterceptor = (
request: InterceptorRequest,
next: (request: InterceptorRequest) => PromiseLike<Response>,
) => PromiseLike<Response> | Response

export interface ResponseError<T = never> extends Error {
data?: T | null
response?: Response | null
}

export class ApiInterceptors {
readonly #interceptors: ApiInterceptor[] = []

Expand All @@ -66,7 +41,7 @@ export class ApiInterceptors {
}
}

export const createFetchApi = () => {
export const createFetchApi = (fetch = globalThis.fetch) => {
const interceptors = new ApiInterceptors()

function fetchApi(
Expand All @@ -90,7 +65,6 @@ export const createFetchApi = () => {
url: string,
options?: FetchApiBaseOptions & { type?: 'json' },
): Promise<T>
// eslint-disable-next-line sonarjs/cognitive-complexity
async function fetchApi(
url: string,
{
Expand Down Expand Up @@ -122,16 +96,8 @@ export const createFetchApi = () => {
if (response.ok) {
return response
}
let data: unknown = null
if (type != null) {
try {
data = await response.clone()[type]()
} catch {
data = await response.clone().text()
}
}
throw Object.assign(new Error(response.statusText), {
data,
data: extractDataFromResponse(response, type),
response,
})
}
Expand All @@ -143,7 +109,8 @@ export const createFetchApi = () => {
headers,
...rest,
})
return type == null ? response : response.clone()[type]()

return type == null ? response : extractDataFromResponse(response, type)
}

return { interceptors, fetchApi }
Expand Down
62 changes: 57 additions & 5 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,65 @@
export type Nullable<T> = T | null | undefined
export type Nil = null | undefined | void

export type Nilable<T> = Nil | T

export type Readonlyable<T> = Readonly<T> | T

export type AnyArray<T = unknown> = Readonlyable<T[]>

export type Arrayable<T, R extends boolean = false> = [R] extends [never]
? T | T[]
: R extends true
? Readonly<T> | readonly T[]
: R extends false
? AnyArray<T> | Readonlyable<T>
: never

export type ValueOf<T> = T[keyof T]

export type URLSearchParametersInit = ConstructorParameters<
export type URLSearchParamsInit = ConstructorParameters<
typeof URLSearchParams
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
>[0]

export type URLSearchParametersOptions =
| Record<string, Nullable<number | string>>
| URLSearchParametersInit
export type URLSearchParamsOptions =
| Record<string, Nilable<Arrayable<number | string>>>
| URLSearchParamsInit
| object

export const ApiMethod = {
GET: 'GET',
POST: 'POST',
PATCH: 'PATCH',
PUT: 'PUT',
DELETE: 'DELETE',
} as const

export type ApiMethod = ValueOf<typeof ApiMethod>

export interface FetchApiBaseOptions
extends Omit<RequestInit, 'body' | 'method'> {
method?: ApiMethod
body?: BodyInit | object
query?: URLSearchParamsOptions
json?: boolean
}

export type ResponseType = 'arrayBuffer' | 'blob' | 'json' | 'text' | null

export interface FetchApiOptions extends FetchApiBaseOptions {
type?: ResponseType
}

export interface InterceptorRequest extends FetchApiOptions {
url: string
}

export type ApiInterceptor = (
request: InterceptorRequest,
next: (request: InterceptorRequest) => PromiseLike<Response>,
) => PromiseLike<Response> | Response

export interface ResponseError<T = never> extends Error {
data?: T | null
response?: Response | null
}
90 changes: 78 additions & 12 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import {
Nullable,
URLSearchParametersInit,
URLSearchParametersOptions,
Nilable,
ResponseType,
URLSearchParamsOptions,
ValueOf,
} from './types.js'

export const CONTENT_TYPE = 'Content-Type'

// eslint-disable-next-line @typescript-eslint/unbound-method
const { toString } = Object.prototype // type-coverage:ignore-line - TODO: report bug
const { toString } = Object.prototype // type-coverage:ignore-line -- https://github.com/plantain-00/type-coverage/issues/133

const objectTag = '[object Object]'

Expand All @@ -22,7 +22,7 @@

for (const _key of Object.keys(input)) {
const key = _key as keyof T
const value = input[key] as Nullable<ValueOf<T>>
const value = input[key] as Nilable<ValueOf<T>>
if (empty ? !value : value == null) {
delete input[key]
} else {
Expand All @@ -33,12 +33,78 @@
return input
}

export const normalizeUrl = (
url: string,
query?: URLSearchParametersOptions,
) => {
const search = new URLSearchParams(
cleanNilValues(query, true) as URLSearchParametersInit,
).toString()
export const normalizeUrl = (url: string, query?: URLSearchParamsOptions) => {
const cleanedQuery = cleanNilValues(query, true)
const searchParams = new URLSearchParams()
if (isPlainObject(cleanedQuery)) {
for (const [
key,
// type-coverage:ignore-next-line -- cannot control
_value,
] of Object.entries(cleanedQuery)) {
const value = _value as unknown
if (Array.isArray(value)) {
const items = value as unknown[]
for (const item of items) {
searchParams.append(key, String(item))
}
} else {
searchParams.set(key, String(value))
}
}
}
const search = searchParams.toString()
return search ? url + (url.includes('?') ? '&' : '?') + search : url
}

export async function extractDataFromResponse(
res: Response,
type: null,
): Promise<Response>
export async function extractDataFromResponse(
res: Response,
type: 'arrayBuffer',
): Promise<ArrayBuffer>
export async function extractDataFromResponse(
res: Response,
type: 'blob',
): Promise<Blob>
export async function extractDataFromResponse<T>(
res: Response,
type: 'json',
): Promise<T>
export async function extractDataFromResponse(
res: Response,
type: 'text',
): Promise<string>
export async function extractDataFromResponse(
res: Response,
type: ResponseType,
): Promise<unknown>
// eslint-disable-next-line sonarjs/cognitive-complexity
export async function extractDataFromResponse(
res: Response,
type: ResponseType,
) {
let data: unknown
if (type != null) {
if (type === 'json' || type === 'text') {
try {
// data could be empty text
data = await res.clone().text()
} catch {}
if (type === 'json' && (data = (data as string).trim())) {
try {
data = JSON.parse(data as string)
} catch {}
}
} else {
try {
data = await res.clone()[type]()
} catch {
data = await res.clone().text()

Check warning on line 105 in src/utils.ts

View check run for this annotation

Codecov / codecov/patch

src/utils.ts#L105

Added line #L105 was not covered by tests
}
}
}
return data
}
54 changes: 54 additions & 0 deletions test/utils.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/* eslint-disable unicorn/no-await-expression-member */

import {
cleanNilValues,
extractDataFromResponse,
isPlainObject,
normalizeUrl,
} from 'x-fetch'

test('isPlainObject', () => {
expect(isPlainObject({})).toBe(true)
expect(isPlainObject([])).toBe(false)
expect(isPlainObject(0)).toBe(false)
expect(isPlainObject(true)).toBe(false)
})

test('cleanNilValues', () => {
expect(cleanNilValues('')).toBe('')
expect(cleanNilValues(true)).toBe(true)
expect(cleanNilValues({ foo: 'bar' })).toEqual({ foo: 'bar' })
expect(cleanNilValues({ foo: 'bar', test: null })).toEqual({ foo: 'bar' })
expect(cleanNilValues({ foo: 'bar', test: '' })).toEqual({
foo: 'bar',
test: '',
})
expect(cleanNilValues({ foo: 'bar', test: '' }, true)).toEqual({ foo: 'bar' })
})

test('normalizeUrl', () => {
expect(normalizeUrl('')).toBe('')
expect(normalizeUrl('', { foo: 'bar' })).toBe('?foo=bar')
expect(normalizeUrl('', { foo: ['bar', 'baz'] })).toBe('?foo=bar&foo=baz')
expect(normalizeUrl('test?x=y')).toBe('test?x=y')
expect(normalizeUrl('test?x=y', { foo: 'bar' })).toBe('test?x=y&foo=bar')
expect(normalizeUrl('test?x=y', { foo: ['bar', 'baz'] })).toBe(
'test?x=y&foo=bar&foo=baz',
)
})

test('extractDataFromResponse', async () => {
expect(await extractDataFromResponse(new Response(''), null)).toBe(undefined)
expect(await extractDataFromResponse(new Response(), null)).toBe(undefined)
expect(await extractDataFromResponse(new Response(), 'text')).toBe('')
expect(await extractDataFromResponse(new Response(null), 'text')).toBe('')
expect(await extractDataFromResponse(new Response('foo'), 'text')).toBe('foo')
expect(await extractDataFromResponse(new Response('foo'), 'json')).toBe('foo')
expect(
await extractDataFromResponse(new Response('{"foo":"bar"}'), 'json'),
).toEqual({ foo: 'bar' })
expect(
(await extractDataFromResponse(new Response('foo'), 'arrayBuffer'))
.byteLength,
).toBe(3)
})
Loading