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

如何将自动生成的Prisma枚举映射为GraphQL/TypeScript枚举?

问题:Prisma与GraphQL枚举类型不匹配的解决思路

我在应用中定义了如下货币枚举:

enum Currency {
  GBP
  USD
}

Prisma生成PrismaClient及对应类型时,会把这类枚举转换为TypeScript类型别名而非TS枚举:

export const Currency: {
  GBP: 'GBP',
  USD: 'USD'
};

export type Currency = (typeof Currency)[keyof typeof Currency]

而我的GraphQL Schema中同样定义了该货币枚举:

enum Currency {
  GBP
  USD
}

通过codegen转换后得到的是标准TS枚举:

export enum Currency {
  GBP = 'GBP',
  USD = 'USD'
}

这就导致查询解析器从Prisma获取货币数据时,返回类型与GraphQL预期类型不匹配。我现在有两个疑问:

  • 能否让Prisma直接生成TS枚举而非类型别名?
  • 或者有没有办法通过codegen映射等方式实现两种类型的转换?

我尝试了一种解决方案,但不确定是否最优:更新codegen配置使用自定义映射器:

schema: "./src/typeDefs/index.ts"
generates:
  ./src/types.d.ts:
    config:
      useIndexSignature: true
      namingConvention:
        enumValues: keep
      scalars:
        UUID: string
        Decimal: Decimal
        DateTime: Date
      mappers:
        Product: ./interfaces/index.ts#Product // 该Product类型包含货币枚举字段
    plugins:
      - typescript
      - typescript-resolvers
      - add:
          content: "import Decimal from 'decimal.js'"
require:
  - tsconfig-paths/register

同时定义了自定义类型覆盖:

// 自定义覆盖类型
import Prisma from "@prisma/client";

export interface Product extends Omit<Prisma.Product, "currency"> {
  currency: Prisma.Currency;
}

不过我不清楚为什么将currency重新设置为原值就能生效,还需要进一步排查。


内容的提问来源于stack exchange,提问作者Stretch0

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 11:17:22