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: return blob if content-type isn't text, svg, xml or json #39

Merged
merged 11 commits into from
Dec 17, 2021
Merged

Conversation

danielroe
Copy link
Member

@danielroe danielroe commented Dec 14, 2021

resolves #38

For binary content types, $fetch will instead return a Blob object.

You can optionally specify blob, arrayBuffer or text to force parsing the body with the respective FetchResponse method.

// Use JSON.parse
await $fetch('/movie?lang=en', { parseResponse: JSON.parse })

// Return text as is
await $fetch('/movie?lang=en', { parseResponse: txt => txt })

// Get the blob version of the response
await $fetch('/api/generate-image', { responseType: 'blob' })

Typing

$fetch('api') // Promise<any>
$fetch<boolean>('api') // Promise<boolean>
$fetch<boolean>('api', { responseType: 'text' }) // Type '"text"' is not assignable to type '"json" | undefined'.ts(2322)
$fetch('api', { responseType: 'json' }) // Promise<any>
$fetch<boolean>('api', { responseType: 'json' }) // Promise<boolean>
$fetch('api', { responseType: 'text' }) // Promise<string>
$fetch('api', { responseType: 'arrayBuffer' }) // Promise<ArrayBuffer>
$fetch('api', { responseType: 'blob' }) // Promise<Blob>

@danielroe danielroe added the enhancement New feature or request label Dec 14, 2021
@danielroe danielroe requested a review from pi0 December 14, 2021 15:06
@danielroe danielroe self-assigned this Dec 14, 2021
src/utils.ts Outdated Show resolved Hide resolved
src/fetch.ts Outdated Show resolved Hide resolved
src/fetch.ts Outdated Show resolved Hide resolved
src/utils.ts Outdated Show resolved Hide resolved
test/index.test.mjs Show resolved Hide resolved
src/utils.ts Outdated
const jsonTypes = new Set(['application/json', 'application/ld+json'])

// This provides reasonable defaults for the correct parser based on Content-Type header.
export function detectContentMethod (_contentType = ''): 'text' | 'blob' | 'json' | 'arrayBuffer' {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would make a type for return type to reuse with ResponseType

@pi0 pi0 merged commit 1029b9e into main Dec 17, 2021
@pi0 pi0 deleted the feat/blob branch December 17, 2021 09:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Blob method does not exist in the result
2 participants