All files / owid-grapher/explorer/urlMigrations ExplorerUrlMigrationUtils.ts

93.75% Statements 30/32
75% Branches 6/8
100% Functions 2/2
93.75% Lines 30/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 451x 1x 1x 1x 1x 1x 8x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 13x 11x 11x 13x 13x                          
import { QueryParams } from "../../clientUtils/urls/UrlUtils"
import { Url } from "../../clientUtils/urls/Url"
import { EXPLORERS_ROUTE_FOLDER } from "../ExplorerConstants"
import { identity, omit } from "../../clientUtils/Util"
 
export const decodeURIComponentOrUndefined = (value: string | undefined) =>
    value !== undefined
        ? decodeURIComponent(value.replace(/\+/g, "%20"))
        : undefined
 
export type QueryParamTransformMap = Record<
    string,
    {
        newName?: string
        transformValue?: (value: string | undefined) => string | undefined
    }
>
 
export const transformQueryParams = (
    oldQueryParams: Readonly<QueryParams>,
    transformMap: QueryParamTransformMap
) => {
    const newQueryParams = omit(
        oldQueryParams,
        ...Object.keys(transformMap)
    ) as QueryParams
    for (const oldParamName in transformMap) {
        if (!(oldParamName in oldQueryParams)) continue
        const { newName, transformValue } = transformMap[oldParamName]
        const name = newName ?? oldParamName
        const transform = transformValue ?? identity
        newQueryParams[name] = transform(oldQueryParams[oldParamName])
    }
    return newQueryParams
}
 
export const getExplorerSlugFromUrl = (url: Url): string | undefined => {
    if (!url.pathname) return undefined
    const match = url.pathname.match(
        new RegExp(`^\/+${EXPLORERS_ROUTE_FOLDER}\/+([^\/]+)`)
    )
    if (match && match[1]) return match[1]
    return undefined
}