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

Serverless部署NestJS GraphQL服务时出现Schema类型重复错误

问题根因

本地运行正常但Serverless Offline报错的核心原因是serverless-plugin-typescript插件的默认编译逻辑会导致NestJS GraphQL的全局类型注册表重复加载模型文件,相同的ObjectType被重复注册到Schema中,才会触发命名唯一校验错误。

解决方案

按优先级排序尝试:

方案1:调整打包逻辑,预编译后再启动Serverless Offline(优先推荐,根治率最高)

serverless-plugin-typescript的增量/实时编译逻辑是问题源头,直接替换为Nest官方的构建流程即可:

  1. 先执行Nest构建命令生成编译产物:
npm run build
  1. 修改serverless.yml配置:
app: server
service: server-api
useDotenv: true

package:
  patterns:
    - 'dist/**' # 改为包含编译后的dist目录
    - '!src/seeds/**'
    - 'node_modules/**' # 保留依赖

# 移除serverless-plugin-typescript插件
plugins:
  - serverless-offline

provider:
  name: aws
  profile: serverless-admin
  runtime: nodejs14.x # 建议升级Node版本,12.x已经停止维护
  lambdaHashingVersion: 20201221

functions:
  main:
    handler: dist/lambda.handler # 改为指向dist目录的handler
    events:
      - http:
          path: graphql
          method: POST
          cors: true
          integration: LAMBDA
      - http:
          path: graphql
          method: GET
          cors: true
          integration: LAMBDA
      - http:
          path: playground
          method: ANY
          cors: true
          integration: LAMBDA
  1. 后续启动Serverless Offline前先执行npm run build即可,不需要再依赖TS实时编译插件。

方案2:如果要保留serverless-plugin-typescript,修改配置禁用缓存和增量编译

在serverless.yml中添加custom配置:

custom:
  serverlessPluginTypescript:
    tsConfigFileLocation: './tsconfig.json'
    skipCheck: true
  serverless-offline:
    allowCache: false # 禁用缓存,避免重复加载模块

方案3:补充嵌套ObjectType的导出,避免隐式加载重复注册

你当前character.model.ts中的Constellation类没有显式export,会导致模块加载时可能被重复解析,补充导出即可:

// character.model.ts 中修改
@ObjectType('Constellation')
export class Constellation { // 补充export关键字
  // 原有字段逻辑不变
}

同时可以在GraphQLModule.forRoot配置中添加orphanedTypes参数,显式注册所有嵌套的ObjectType,避免自动扫描时重复加载:

// app.module.ts
import { Constellation } from './character/character.model';
import { Affix } from './artifact-set/artifact-set.model';

GraphQLModule.forRoot({
  // 原有配置保持不变
  orphanedTypes: [Constellation, Affix],
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 02:24:05