Skip to content

Commit

Permalink
Remove useless object param values support in getUrlOrPathWithQueryPa…
Browse files Browse the repository at this point in the history
…rams() util
  • Loading branch information
ivangabriele committed Mar 27, 2024
1 parent 4100a38 commit 5e24f7b
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 34 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,6 @@ describe('getUrlOrPathWithQueryParams', () => {
expect(result).toBe('/example?colors=blue,green,red')
})

it('should handle nested objects correctly', () => {
const path = '/example'
const queryParams = { user: { age: '30', name: 'John' } }

const result = getUrlOrPathWithQueryParams(path, queryParams)

expect(result).toBe('/example?user.age=30&user.name=John')
})

it('should exclude undefined or null values', () => {
const path = '/example'
const queryParams = { age: undefined, location: null, name: 'John' }
Expand Down
33 changes: 8 additions & 25 deletions frontend/src/utils/getUrlOrPathWithQueryParams.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,26 @@
import { isObject } from './isObject'
type QueryParamValue = number | string | boolean | Array<number | string> | null | undefined

import type { AnyObject } from '@mtes-mct/monitor-ui'

const sortByKey = (a: [string, any], b: [string, any]): number => {
const sortByKey = (a: [string, QueryParamValue], b: [string, QueryParamValue]): number => {
const [keyA] = a
const [keyB] = b

return keyA.localeCompare(keyB)
}

function getUrlQueryParamFromObjectEntry(key: string, value: any): string {
if (Array.isArray(value)) {
return `${key}=${[...value].sort().join(',')}`
}

if (isObject(value)) {
return Object.entries(value)
.sort(sortByKey)
.reduce((queryParamAsString, [nestedKey, nestedValue]) => {
if (nestedValue === undefined) {
return queryParamAsString
}

return `${queryParamAsString}${queryParamAsString ? '&' : ''}${key}.${nestedKey}=${nestedValue}`
}, '')
export function getUrlOrPathWithQueryParams(
urlOrPath: string,
queryParamsAsObject: {
[key: string]: QueryParamValue
}

return `${key}=${value}`
}

export function getUrlOrPathWithQueryParams(urlOrPath: string, queryParamsAsObject: AnyObject): string {
): string {
const queryParamsAsString = Object.entries(queryParamsAsObject)
.sort(sortByKey)
.reduce((queryParamsAsStringAcc, [key, value]) => {
if (value === undefined || value === null) {
return queryParamsAsStringAcc
}

const queryParamAsString = getUrlQueryParamFromObjectEntry(key, value)
const queryParamAsString = Array.isArray(value) ? `${key}=${[...value].sort().join(',')}` : `${key}=${value}`

return `${queryParamsAsStringAcc}${queryParamsAsStringAcc ? '&' : ''}${queryParamAsString}`
}, '')
Expand Down

0 comments on commit 5e24f7b

Please sign in to comment.