Skip to content

Commit

Permalink
šŸ› fix: objToQuery format (#100)
Browse files Browse the repository at this point in the history
  • Loading branch information
rustin01 authored Aug 7, 2024
1 parent e522b1f commit f53471d
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 23 deletions.
14 changes: 0 additions & 14 deletions apps/wallet/src/utils/url.ts

This file was deleted.

24 changes: 24 additions & 0 deletions apps/wallet/src/utils/url/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { expect, test } from 'vitest'
import { objToQuery, queryToObj } from '.'

test('obj to query', () => {
const obj = {
a: 1,
c: '3',
e: ['5', '6'],
f: { g: 7, h: 8 },
}
expect(objToQuery(obj)).toBe(
'a=1&c=3&e=%5B%225%22%2C%226%22%5D&f=%7B%22g%22%3A7%2C%22h%22%3A8%7D'
)
})

test('query to obj', () => {
const query = 'a=1&c=3&e=%5B%225%22%2C%226%22%5D&f=%7B%22g%22%3A7%2C%22h%22%3A8%7D'
expect(queryToObj(query)).toStrictEqual({
a: '1',
c: '3',
e: ['5', '6'],
f: { g: 7, h: 8 },
})
})
23 changes: 23 additions & 0 deletions apps/wallet/src/utils/url/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
export const objToQuery = <T extends object>(obj: T, delimiter: string = '&') => {
return Object.entries(obj)
.map(([key, value]) => `${key}=${encodeURIComponent(typeof value === 'object' ? JSON.stringify(value) : String(value))}`)
.join(delimiter)
}

export const queryToObj = <T extends object>(query: string, delimiter: string = '&') => {
return Object.fromEntries(
query
.split(delimiter)
.map((str) => str.split('='))
.map(([key, value]) => {
let val = String(value)
try {
const parsed = JSON.parse(decodeURIComponent(value))
if (typeof parsed === 'object') {
val = parsed
}
} catch (e) {}
return [key, val]
})
) as T
}
6 changes: 0 additions & 6 deletions apps/wallet/src/utils/vitest-example/sum.test.ts

This file was deleted.

3 changes: 0 additions & 3 deletions apps/wallet/src/utils/vitest-example/sum.ts

This file was deleted.

0 comments on commit f53471d

Please sign in to comment.