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: support automatic json body for post requests #7

Merged
merged 8 commits into from
Feb 19, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
18 changes: 16 additions & 2 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ export type FetchRequest = RequestInfo

export interface SearchParams { [key: string]: any }

export interface FetchOptions extends RequestInit {
export interface FetchOptions extends Omit<RequestInit, 'body'> {
baseURL?: string
body?: RequestInit['body'] | Record<string, any>
params?: SearchParams
response?: boolean
}
Expand All @@ -31,8 +32,21 @@ export function createFetch ({ fetch }: CreateFetchOptions): $Fetch {
if (opts.params) {
request = withQuery(request, opts.params)
}
if (opts.body && typeof opts.body === 'object' && ['patch', 'post', 'put'].includes(opts.method?.toLowerCase() || '')) {
danielroe marked this conversation as resolved.
Show resolved Hide resolved
danielroe marked this conversation as resolved.
Show resolved Hide resolved
try {
opts.body = JSON.stringify(opts.body)
opts.headers = opts.headers || {}
if (Array.isArray(opts.headers)) {
opts.headers.push(['content-type', 'application/json'])
danielroe marked this conversation as resolved.
Show resolved Hide resolved
} else if ('set' in opts.headers) {
;(opts.headers as Headers).set('content-type', 'application/json')
} else {
opts.headers['content-type'] = 'application/json'
}
} catch {}
danielroe marked this conversation as resolved.
Show resolved Hide resolved
}
}
const response: FetchResponse<any> = await fetch(request, opts)
const response: FetchResponse<any> = await fetch(request, opts as RequestInit)
const text = await response.text()
response.data = destr(text)
if (!response.ok) {
Expand Down
7 changes: 6 additions & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { listen, Listener } from 'listhen'
import { getQuery } from 'ufo'
import { createApp } from 'h3'
import { createApp, useBody } from 'h3'
import { $fetch, FetchError } from '../src/node'

describe('ohmyfetch', () => {
Expand All @@ -11,6 +11,7 @@ describe('ohmyfetch', () => {
.use('/ok', () => 'ok')
.use('/params', req => (getQuery(req.url || '')))
.use('/url', req => req.url)
.use('/post', req => useBody(req))
listener = await listen(app)
})

Expand All @@ -26,6 +27,10 @@ describe('ohmyfetch', () => {
expect(await $fetch('/x?foo=123', { baseURL: listener.getURL('url') })).toBe('/x?foo=123')
})

it('posts ', async () => {
expect(await $fetch(listener.getURL('post'), { method: 'POST', body: { num: 42 } as any })).toEqual({ num: 42 })
})

it('404', async () => {
const err: FetchError = await $fetch(listener.getURL('404')).catch(err => err)
expect(err.stack).toMatch('404 Not Found')
Expand Down