Skip to content

Commit

Permalink
Enable FormData as input
Browse files Browse the repository at this point in the history
  • Loading branch information
voxpelli committed Oct 28, 2022
1 parent 2e0d66e commit ccdb224
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
20 changes: 15 additions & 5 deletions src/fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,14 @@ function getQuery(
return queryString(queryObj)
}

function getHeaders(body?: string, init?: HeadersInit) {
function getHeaders(body?: CustomRequestInit['body'], init?: HeadersInit) {
const headers = new Headers(init)

if (body !== undefined && !headers.has('Content-Type')) {
if (
body !== undefined &&
!(body instanceof FormData) &&
!headers.has('Content-Type')
) {
headers.append('Content-Type', 'application/json')
}

Expand All @@ -86,8 +90,11 @@ function getHeaders(body?: string, init?: HeadersInit) {
return headers
}

function getBody(method: Method, payload: any) {
const body = sendBody(method) ? JSON.stringify(payload) : undefined
function getBody(method: Method, payload: unknown): CustomRequestInit['body'] {
if (!sendBody(method)) {
return
}
const body = payload instanceof FormData ? payload : JSON.stringify(payload)
// if delete don't send body if empty
return method === 'delete' && body === '{}' ? undefined : body
}
Expand All @@ -108,7 +115,10 @@ function mergeRequestInit(
return { ...first, ...second, headers }
}

function getFetchParams(request: Request) {
function getFetchParams(request: Request): {
url: string
init: CustomRequestInit
} {
// clone payload
// if body is a top level array [ 'a', 'b', param: value ] with param values
// using spread [ ...payload ] returns [ 'a', 'b' ] and skips custom keys
Expand Down
14 changes: 10 additions & 4 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,18 @@ export type OpArgType<OP> = OP extends {
}
// openapi 3
requestBody?: {
content: {
'application/json': infer RB
}
content:
| {
'application/json': infer RB
}
| {
'multipart/form-data': infer FD
}
}
}
? P & Q & (B extends Record<string, unknown> ? B[keyof B] : unknown) & RB
? FD extends Record<string, string>
? FormData
: P & Q & (B extends Record<string, unknown> ? B[keyof B] : unknown) & RB
: Record<string, never>

type OpResponseTypes<OP> = OP extends {
Expand Down

0 comments on commit ccdb224

Please sign in to comment.