All Downloads are FREE. Search and download functionalities are using the official Maven repository.

core.Expression.propsResolver.ts Maven / Gradle / Ivy

The newest version!
import isObject from 'lodash/isObject'
import uniq from 'lodash/uniq'

import { parseExpression } from './parse'
import { executeExpression } from './execute'

const blackList = [
    'dataProvider',
    'action',
    'actions',
    'queryMapping',
    'pathMapping',
]

type _Map = {
    [K in keyof T]: Resolve
}
export type Resolve = T extends readonly unknown[]
    ? _Map
    : T extends Record
        ? _Map
        : T extends `\`${string}\``
            ? unknown
            : T

// FIXME: Разобраться почему он нормально не понимает тип аргумента и результата, убрать "as Resolve"
export function propsResolver<
    Resolved extends Resolve,
    Prop = unknown,
>(
    prop: Prop,
    model: Record | Array> = {},
    expressionContext: Record = {},
    ignoreKeys?: string[],
): Resolved {
    const ignore = ignoreKeys ? uniq([...blackList, ...ignoreKeys]) : blackList

    function resolve(prop: T): Resolve {
        if (!prop) { return prop as Resolve }
        if (typeof prop === 'string') {
            const parsedExpression = parseExpression(prop)

            if (parsedExpression) {
                return executeExpression(parsedExpression, model, expressionContext)
            }
        }
        if (typeof prop === 'function') { return prop as Resolve }
        if (Array.isArray(prop)) {
            return prop.map(resolve) as Resolve
        }

        if (isObject(prop)) {
            return Object.fromEntries(Object.entries(prop).map(([key, property]) => [
                key,
                ignore.includes(key) ? property : resolve(property),
            ])) as Resolve
        }

        return prop as Resolve
    }

    return resolve(prop) as Resolved
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy