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
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
25 changes: 15 additions & 10 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export type FetchRequest = RequestInfo

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

const payloadMethods = ['patch', 'post', 'put']

export interface FetchOptions extends Omit<RequestInit, 'body'> {
baseURL?: string
body?: RequestInit['body'] | Record<string, any>
Expand All @@ -32,18 +34,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() || '')) {
try {
opts.body = JSON.stringify(opts.body)
opts.headers = opts.headers || {}
if (Array.isArray(opts.headers)) {
opts.headers.push(['content-type', 'application/json'])
} else if ('set' in opts.headers) {
;(opts.headers as Headers).set('content-type', 'application/json')
if (opts.body && opts.body.toString() === '[object Object]' && payloadMethods.includes(opts.method?.toLowerCase() || '')) {
opts.body = JSON.stringify(opts.body)
opts.headers = opts.headers || {}
if (Array.isArray(opts.headers)) {
const index = opts.headers.findIndex(([header]) => header.toLowerCase() === 'content-type')
if (index >= 0) {
danielroe marked this conversation as resolved.
Show resolved Hide resolved
opts.headers[index] = ['content-type', 'application/json']
} else {
opts.headers['content-type'] = 'application/json'
opts.headers.push(['content-type', 'application/json'])
}
} catch {}
} else if ('set' in opts.headers) {
;(opts.headers as Headers).set('content-type', 'application/json')
} else {
opts.headers['content-type'] = 'application/json'
}
}
}
const response: FetchResponse<any> = await fetch(request, opts as RequestInit)
Expand Down