|
import flat from 'flat' |
|
|
|
import { DELIMITER } from './constants.js' |
|
import { selectParams } from './select-params.js' |
|
import { FlattenParams, GetOptions } from './flat.types.js' |
|
import { propertyKeyRegex } from './property-key-regex.js' |
|
|
|
const TEMP_HOLDING_KEY = 'TEMP_HOLDING_KEY' |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const get = (params: FlattenParams = {}, propertyPath?: string, options?: GetOptions): any => { |
|
if (!propertyPath) { |
|
return flat.unflatten(params) |
|
} |
|
|
|
|
|
|
|
|
|
if (Object.keys(params).find((key) => (key === propertyPath))) { |
|
return params[propertyPath] |
|
} |
|
|
|
const regex = propertyKeyRegex(propertyPath, options) |
|
const selectedParams = selectParams(params, propertyPath, options) |
|
|
|
const nestedProperties = Object.keys(selectedParams).reduce((memo, key, index) => { |
|
let newKey = key.replace(regex, `${TEMP_HOLDING_KEY}${DELIMITER}`) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if (options?.includeAllSiblings) { |
|
newKey = newKey.replace( |
|
new RegExp(`${TEMP_HOLDING_KEY}\\${DELIMITER}(\\d*)`), |
|
`${TEMP_HOLDING_KEY}${DELIMITER}${index}`, |
|
) |
|
} |
|
|
|
memo[newKey] = selectedParams[key] |
|
|
|
return memo |
|
}, {} as FlattenParams) |
|
|
|
if (Object.keys(nestedProperties).length) { |
|
return (flat.unflatten(nestedProperties) as Record<string, unknown>)[TEMP_HOLDING_KEY] |
|
} |
|
return undefined |
|
} |
|
|
|
export { get } |
|
|