Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
29 changes: 13 additions & 16 deletions src/fetch/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,6 @@ export const edenFetch = <App extends Elysia<any, any, any, any, any, any, any>>
endpoint = endpoint.replace(`:${key}`, value as string)
})

// @ts-ignore
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 nonNullishQuery = query
Expand All @@ -85,14 +77,19 @@ export const edenFetch = <App extends Elysia<any, any, any, any, any, any, any>>
: ''

const requestUrl = `${server}${endpoint}${queryStr}`
const headers = body
? {
'content-type': 'application/json',
// @ts-ignore
...options.headers
}
: // @ts-ignore
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,
// @ts-ignore
Expand Down
29 changes: 28 additions & 1 deletion test/fetch.test.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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',
Expand Down Expand Up @@ -165,6 +176,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', {
Expand Down