You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简化含if-else分支的Prisma统计代码以降低复杂度?

简化Prisma多渠道客户统计代码的方案

原代码的问题很明显:重复逻辑冗余,if-else分支里仅差一个location_id条件,三个渠道的查询逻辑几乎完全一致,完全可以把重复部分抽出来优化。

方案一:提取公共条件+并行查询

把固定查询条件抽成公共对象,动态添加location_id,再通过循环+Promise.all并行处理三个渠道的统计——既减少代码量,还能把原来的串行查询改成并行,提升效率:

// 定义要统计的渠道列表
const channels = ['ANDROID', 'IOS', 'WEBSITE'];
// 构建基础查询条件,动态判断是否加入location_id
const baseWhere = {
  ref: headerData?.ref,
  ...(location_id ? { location_id } : {})
};

// 并行执行所有统计请求
const [android_devices, ios_devices, web_devices] = await Promise.all(
  channels.map(channel => 
    PRISMA.customers.count({
      where: {
        ...baseWhere,
        channel
      }
    })
  )
);

方案二:用groupBy一次性查询所有渠道(更高效)

如果你的Prisma版本支持groupBy,可以直接通过一次数据库查询拿到所有渠道的统计结果,避免多次请求数据库,性能更优:

const stats = await PRISMA.customers.groupBy({
  by: ['channel'], // 按channel字段分组
  _count: { _all: true }, // 统计每组的总数量
  where: {
    ref: headerData?.ref,
    ...(location_id ? { location_id } : {}),
    channel: { in: ['ANDROID', 'IOS', 'WEBSITE'] } // 指定仅统计目标渠道
  }
});

// 把分组结果映射成需要的变量
const countMap = stats.reduce((map, item) => {
  const key = `${item.channel.toLowerCase()}_devices`;
  map[key] = item._count._all;
  return map;
}, {});

const { android_devices, ios_devices, web_devices } = countMap;

两种方案都能彻底消除原代码里的if-else分支和重复逻辑:方案一保留了原有的变量结构,方案二则更适合追求性能优化的场景。

内容的提问来源于stack exchange,提问作者Prajwal K Rao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 22:15:30