如何将字符串数组转换为 Prisma Select 语句

How to Convert String Array into Prisma Select Statement

我想动态地 select Prisma 列,我从客户端得到这个:

['id', 'createdAt', 'updatedAt', 'Order.id', 'Order.Item.id', 'Order.Item.desc']

我想改成这样:

{id: true, createdAt: true, updatedAt: true, Order: {select: {id: true, Item: {select: {id: true, desc: true}}}}

这样我就可以在 Prisma 查询中使用它,例如:

prisma.sales.findMany({where: {id: {_eq: 1}}, select: {id: true, createdAt: true, updatedAt: true, Order: {select: {id: true, Item: {select: {id: true, desc: true}}}}}})

您可以构建一个简单的递归函数来构建对象并填充嵌套属性:

const objPaths = ['id', 'createdAt', 'updatedAt', 'Order.id', 'Order.Item.id', 'Order.Item.desc'];


function buildObject(paths) {
    const result = {};
    for (const path of paths) {
        const pathParts = path.split(".");
        if (pathParts.length > 1) {
            populateNested(result, pathParts, 0);
        } else {
            result[path] = true;
        }
    }
    return result;
}

function populateNested(parent, paths, currPathIndex) {
    if (currPathIndex === paths.length - 1) {
        parent[paths[currPathIndex]] = true;
    } else {
        let currObj = {select: {}};
        if (parent[paths[currPathIndex]]) {
            currObj = parent[paths[currPathIndex]];
        }
        parent[paths[currPathIndex]] = currObj;
        populateNested(currObj.select, paths, currPathIndex + 1);
    }

}

console.log(JSON.stringify(buildObject(objPaths), null, 2));