From 159b9a57dde08d9a25477918881896d3663db2d8 Mon Sep 17 00:00:00 2001 From: Pelle Wessman Date: Sat, 29 Oct 2022 00:35:13 +0200 Subject: [PATCH] Enable FormData as input Fixes #31 --- src/fetcher.ts | 20 +++++++++++++++----- src/types.ts | 6 ++++-- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/fetcher.ts b/src/fetcher.ts index 1eb1d5f9..f219a6d2 100644 --- a/src/fetcher.ts +++ b/src/fetcher.ts @@ -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') } @@ -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 } @@ -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 diff --git a/src/types.ts b/src/types.ts index 63ff447e..745c4f33 100644 --- a/src/types.ts +++ b/src/types.ts @@ -13,7 +13,7 @@ export type OpenapiPaths = { } } -type JSONBody = +type JSONBody = | { content: { 'application/json': T @@ -45,7 +45,9 @@ export type OpArgType = OP extends { | { 'multipart/form-data': infer FD } } } - ? P & Q & (B extends Record ? B[keyof B] : unknown) & RB + ? FD extends Record + ? FormData + : P & Q & (B extends Record ? B[keyof B] : unknown) & RB : Record type OpResponseTypes = OP extends {