Skip to content

fix(query): exclude null-ish values from query encoding #185

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 5, 2025
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
19 changes: 14 additions & 5 deletions src/fetch/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ const handleResponse = async (response: Response, retry: () => any) => {
}
}

export const edenFetch =
<App extends Elysia<any, any, any, any, any, any, any>>(
export const edenFetch = <App extends Elysia<any, any, any, any, any, any, any>>(
server: string,
config?: EdenFetch.Config
): EdenFetch.Create<App> =>
Expand All @@ -72,9 +71,19 @@ export const edenFetch =
} catch (error) {}

const fetch = config?.fetcher || globalThis.fetch
const queryStr = query
? `?${new URLSearchParams(query).toString()}`
: ''

const nonNullishQuery = query
? Object.fromEntries(
Object.entries(query).filter(
([_, val]) => val !== undefined && val !== null
)
)
: null
Comment on lines +75 to +81
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const nonNullishQuery = query
? Object.fromEntries(
Object.entries(query).filter(
([_, val]) => val !== undefined && val !== null
)
)
: null
const nonNullishQuery = query
? Object.fromEntries(
Object.entries(query).filter(
([_, val]) => val != null)
)
)
: null

js quirk: != null catches both undefined and null

Copy link
Contributor Author

@ShuviSchwarze ShuviSchwarze Feb 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unless for performance reasons, I dont think relying on implicit behaviours is good


const queryStr = nonNullishQuery
? `?${new URLSearchParams(nonNullishQuery).toString()}`
: ''

const requestUrl = `${server}${endpoint}${queryStr}`
const headers = body
? {
Expand Down
9 changes: 7 additions & 2 deletions src/treaty2/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,12 +196,17 @@ const createProxy = (
continue
}

if (typeof value === 'object') {
append(key, JSON.stringify(value))
// Explicitly exclude null and undefined values from url encoding
// to prevent parsing string "null" / string "undefined"
if (value === undefined || value === null) {
continue
}


if (typeof value === 'object') {
append(key, JSON.stringify(value))
continue
}
append(key, `${value}`)
}
}
Expand Down
49 changes: 49 additions & 0 deletions test/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,32 @@ const app = new Elysia()
})
}
)
.get(
'/with-query-undefined',
({ query }) => {
return {
query
}
},
{
query: t.Object({
q: t.Undefined(t.String())
})
}
)
.get(
'/with-query-nullish',
({ query }) => {
return {
query
}
},
{
query: t.Object({
q: t.Nullable(t.String())
})
}
)
.listen(8081)

const fetch = edenFetch<typeof app>('http://localhost:8081')
Expand Down Expand Up @@ -170,4 +196,27 @@ describe('Eden Fetch', () => {
})
expect(data?.query.q).toBe('A')
})

it('send undefined query', async () => {
const { data, error } = await fetch('/with-query-undefined', {
query: {
q: undefined
}
})
expect(data?.query.q).toBeUndefined()
expect(error).toBeNull()
})

// t.Nullable is impossible to represent with query params
// without elysia specifically parsing 'null'
it('send null query', async () => {
const { data, error } = await fetch('/with-query-nullish', {
query: {
q: null
}
})
expect(data?.query.q).toBeUndefined()
expect(error?.status).toBe(422)
expect(error?.value.type).toBe("validation")
})
})
75 changes: 75 additions & 0 deletions test/treaty2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,34 @@ const app = new Elysia()
username: t.String()
})
})
.get('/query-optional', ({ query }) => query, {
query: t.Object({
username: t.Optional(t.String()),
})
})
.get('/query-nullable', ({ query }) => query, {
query: t.Object({
username: t.Nullable(t.String()),
})
})
.get('/queries', ({ query }) => query, {
query: t.Object({
username: t.String(),
alias: t.Literal('Kristen')
})
})
.get('/queries-optional', ({ query }) => query, {
query: t.Object({
username: t.Optional(t.String()),
alias: t.Literal('Kristen')
})
})
.get('/queries-nullable', ({ query }) => query, {
query: t.Object({
username: t.Nullable(t.Number()),
alias: t.Literal('Kristen')
})
})
.post('/queries', ({ query }) => query, {
query: t.Object({
username: t.String(),
Expand Down Expand Up @@ -273,6 +295,32 @@ describe('Treaty2', () => {
expect(data).toEqual(query)
})

// t.Nullable is impossible to represent with query params
// without elysia specifically parsing 'null'
it('get null query', async () => {
const query = { username: null }

const { data, error } = await client['query-nullable'].get({
query
})

expect(data).toBeNull()
expect(error?.status).toBe(422)
expect(error?.value.type).toBe("validation")
})

it('get optional query', async () => {
const query = { username: undefined }

const { data } = await client['query-optional'].get({
query
})

expect(data).toEqual({
username: undefined
})
})

it('get queries', async () => {
const query = { username: 'A', alias: 'Kristen' } as const

Expand All @@ -283,6 +331,33 @@ describe('Treaty2', () => {
expect(data).toEqual(query)
})

it('get optional queries', async () => {
const query = { username: undefined, alias: 'Kristen' } as const

const { data } = await client['queries-optional'].get({
query
})

expect(data).toEqual({
username: undefined,
alias: 'Kristen'
})
})

// t.Nullable is impossible to represent with query params
// without elysia specifically parsing 'null'
it('get nullable queries', async () => {
const query = { username: null, alias: 'Kristen' } as const

const { data, error } = await client['queries-nullable'].get({
query
})

expect(data).toBeNull()
expect(error?.status).toBe(422)
expect(error?.value.type).toBe("validation")
})

it('post queries', async () => {
const query = { username: 'A', alias: 'Kristen' } as const

Expand Down