Skip to content

Commit ccdb224

Browse files
committed
Enable FormData as input
Fixes #31
1 parent 2e0d66e commit ccdb224

File tree

2 files changed

+25
-9
lines changed

2 files changed

+25
-9
lines changed

src/fetcher.ts

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,14 @@ function getQuery(
7272
return queryString(queryObj)
7373
}
7474

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

78-
if (body !== undefined && !headers.has('Content-Type')) {
78+
if (
79+
body !== undefined &&
80+
!(body instanceof FormData) &&
81+
!headers.has('Content-Type')
82+
) {
7983
headers.append('Content-Type', 'application/json')
8084
}
8185

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

89-
function getBody(method: Method, payload: any) {
90-
const body = sendBody(method) ? JSON.stringify(payload) : undefined
93+
function getBody(method: Method, payload: unknown): CustomRequestInit['body'] {
94+
if (!sendBody(method)) {
95+
return
96+
}
97+
const body = payload instanceof FormData ? payload : JSON.stringify(payload)
9198
// if delete don't send body if empty
9299
return method === 'delete' && body === '{}' ? undefined : body
93100
}
@@ -108,7 +115,10 @@ function mergeRequestInit(
108115
return { ...first, ...second, headers }
109116
}
110117

111-
function getFetchParams(request: Request) {
118+
function getFetchParams(request: Request): {
119+
url: string
120+
init: CustomRequestInit
121+
} {
112122
// clone payload
113123
// if body is a top level array [ 'a', 'b', param: value ] with param values
114124
// using spread [ ...payload ] returns [ 'a', 'b' ] and skips custom keys

src/types.ts

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,18 @@ export type OpArgType<OP> = OP extends {
2323
}
2424
// openapi 3
2525
requestBody?: {
26-
content: {
27-
'application/json': infer RB
28-
}
26+
content:
27+
| {
28+
'application/json': infer RB
29+
}
30+
| {
31+
'multipart/form-data': infer FD
32+
}
2933
}
3034
}
31-
? P & Q & (B extends Record<string, unknown> ? B[keyof B] : unknown) & RB
35+
? FD extends Record<string, string>
36+
? FormData
37+
: P & Q & (B extends Record<string, unknown> ? B[keyof B] : unknown) & RB
3238
: Record<string, never>
3339

3440
type OpResponseTypes<OP> = OP extends {

0 commit comments

Comments
 (0)