|
import flat from 'flat' |
|
|
|
import { DELIMITER } from './constants.js' |
|
import { FlattenParams } from './flat.types.js' |
|
import { propertyKeyRegex } from './property-key-regex.js' |
|
import { pathToParts } from './path-to-parts.js' |
|
|
|
const isObject = (value: any): boolean => { |
|
|
|
if (typeof File === 'undefined') { |
|
return typeof value === 'object' && value !== null |
|
} |
|
|
|
return typeof value === 'object' && !(value instanceof File) && value !== null |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const set = (params: FlattenParams = {}, propertyPath: string, value?: any): FlattenParams => { |
|
const regex = propertyKeyRegex(propertyPath) |
|
|
|
|
|
const paramsCopy = Object.keys(params) |
|
.filter((key) => !key.match(regex)) |
|
.reduce((memo, key) => { |
|
memo[key] = params[key] |
|
|
|
return memo |
|
}, {} as FlattenParams) |
|
|
|
if (typeof value !== 'undefined') { |
|
if (isObject(value) && !(value instanceof Date)) { |
|
const flattened = flat.flatten(value) as any |
|
|
|
if (Object.keys(flattened).length) { |
|
Object.keys(flattened).forEach((key) => { |
|
paramsCopy[`${propertyPath}${DELIMITER}${key}`] = flattened[key] |
|
}) |
|
} else if (Array.isArray(value)) { |
|
paramsCopy[propertyPath] = [] |
|
} else { |
|
paramsCopy[propertyPath] = {} |
|
} |
|
} else { |
|
paramsCopy[propertyPath] = value |
|
} |
|
|
|
|
|
|
|
const parts = pathToParts(propertyPath).slice(0, -1) |
|
if (parts.length) { |
|
return Object.keys(paramsCopy) |
|
.filter((key) => !parts.includes(key)) |
|
.reduce((memo, key) => { |
|
memo[key] = paramsCopy[key] |
|
|
|
return memo |
|
}, {} as FlattenParams) |
|
} |
|
} |
|
return paramsCopy |
|
} |
|
|
|
export { set } |
|
|