From 4b1a19a839df40ee90e2ae2300aac05c1e7ffe69 Mon Sep 17 00:00:00 2001 From: Ruben Nogueira Date: Mon, 23 Dec 2024 23:41:21 +0000 Subject: [PATCH] fix: formdata post --- src/fetch/index.ts | 26 +++++++++++++------------- test/fetch.test.ts | 29 ++++++++++++++++++++++++++++- 2 files changed, 41 insertions(+), 14 deletions(-) diff --git a/src/fetch/index.ts b/src/fetch/index.ts index 4682426..c4b1767 100644 --- a/src/fetch/index.ts +++ b/src/fetch/index.ts @@ -63,24 +63,24 @@ export const edenFetch = endpoint = endpoint.replace(`:${key}`, value as string) }) - const contentType = options.headers?.['Content-Type'] - - if (!contentType || contentType === 'application/json') - try { - body = JSON.stringify(body) - } catch (error) {} - const fetch = config?.fetcher || globalThis.fetch const queryStr = query ? `?${new URLSearchParams(query).toString()}` : '' const requestUrl = `${server}${endpoint}${queryStr}` - const headers = body - ? { - 'content-type': 'application/json', - ...options.headers - } - : options.headers + const headers = new Headers(options.headers || {}) + const contentType = headers.get('content-type') + if ( + !(body instanceof FormData) && + !(body instanceof URLSearchParams) && + (!contentType || contentType === 'application/json') + ) { + try { + body = JSON.stringify(body) + if (!contentType) headers.set('content-type', 'application/json') + } catch (error) {} + } + const init = { ...options, method: options.method?.toUpperCase() || 'GET', diff --git a/test/fetch.test.ts b/test/fetch.test.ts index d9a5c51..600c3f7 100644 --- a/test/fetch.test.ts +++ b/test/fetch.test.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/no-unused-vars */ -import { Elysia, t } from 'elysia' +import { Elysia, form, t } from 'elysia' import { edenFetch } from '../src' import { describe, expect, it, beforeAll } from 'bun:test' @@ -13,6 +13,17 @@ const json = { const app = new Elysia() .get('/', () => 'hi') .post('/', () => 'post') + .post('/form-data', ({ body }) => { + return { + file: body.file.name, + size: body.file.size + } + }, { + body: t.Object({ + file: t.File() + }), + parse: 'formdata' + }) .get('/json', ({ body }) => json) .get( '/json-utf8', @@ -139,6 +150,22 @@ describe('Eden Fetch', () => { expect(data).toEqual(false) }) + it('parse form data', async () => { + const formData = new FormData(); + formData.append('file', new File(['test'], 'test.txt', { type: 'text/plain' })) + + const { data } = await fetch('/form-data', { + method: 'POST', + // @ts-ignore + body: formData + }) + + expect(data).toEqual({ + file: 'test.txt', + size: 4 + }) + }) + // ! FIX ME // it('handle throw error', async () => { // const { data, error } = await fetch('/throw-error', {