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

如何获取供delegateToSchema使用的GraphQL subschema

如何获取delegateToSchema所需的subschema实例

delegateToSchema要求传入的subschema是可执行的GraphQLSchema实例,不能只是原始的typeDefs字符串,你需要先为booking schema单独构造可执行实例,再导入使用。

步骤1:构造独立的booking可执行子schema

在你的booking schema对应文件中,使用makeExecutableSchema构造可执行实例并导出:

// bookingSchema.js
import { makeExecutableSchema } from '@graphql-tools/schema'
import { readFileSync } from 'fs'

// 如果你的schema写在独立的.graphql文件中,用fs读取即可
const bookingTypeDefs = readFileSync('./booking.graphql', 'utf8')

// booking自身的查询resolver,即原生查询booking数据的业务逻辑
const bookingResolvers = {
  Query: {
    booking: async (_, { id }) => {
      // 你的原有booking查询逻辑,比如查数据库/调用接口
      return await db.booking.findUnique({ where: { id } })
    }
  }
}

// 导出的这个就是你需要的subschema
export const bookingSubschema = makeExecutableSchema({
  typeDefs: bookingTypeDefs,
  resolvers: bookingResolvers
})

步骤2:在resolver文件中导入并使用subschema

直接导入上一步导出的bookingSubschema传入delegateToSchema即可:

// resolvers.js
import { delegateToSchema } from '@graphql-tools/delegate'
import { bookingSubschema } from './bookingSchema.js'

export const resolvers = {
  Query: {
    // 你的users查询原有逻辑
    users: async () => {
      return await db.user.findMany()
    }
  },
  User: {
    booking: (parent, args, context, info) => delegateToSchema({
      schema: bookingSubschema,
      operation: 'query',
      fieldName: 'booking',
      args: { id: parent.bookingId }, // 注意和User类型的字段名匹配,不要写错成booking_id
      context,
      info
    })
  }
}

步骤3:使用stitchSchemas构造最终可执行schema

你之前使用的mergeTypeDefs仅合并类型定义,不支持跨schema委托逻辑,需要替换为@graphql-tools/stitch的stitchSchemas构造最终schema:

// 入口schema构造文件
import { stitchSchemas } from '@graphql-tools/stitch'
import { bookingSubschema } from './bookingSchema.js'
import { readFileSync } from 'fs'
import { resolvers } from './resolvers.js'

// 读取独立的user schema文件内容
const userTypeDefs = readFileSync('./user.graphql', 'utf8')

export const finalExecutableSchema = stitchSchemas({
  subschemas: [bookingSubschema],
  typeDefs: userTypeDefs,
  resolvers: resolvers
})

常见问题说明

  • 如果你之前用loadSchema不生效,是因为loadSchema一般用于加载远程schema或需特殊处理的外部schema,本地自用的子schema直接用makeExecutableSchema构造更简单
  • 所有子schema必须是可执行实例,不能仅传入原始typeDefs字符串
  • 注意参数名和字段名匹配,避免拼写错误导致查询为空

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:36:01