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

使用Neo4j GraphQL库时,如何从GraphQL Schema获取Resolvers?

从Neo4j GraphQL自动生成的Schema中获取Resolvers

是的,你可以通过GraphQLSchema对象的内置方法提取自动生成的Resolvers,以下是具体实现方式:

核心方法:通过Schema类型字段提取

当你使用Neo4jGraphQL类构建并获取Schema后,可以通过getQueryType()、getMutationType()等方法获取对应的根类型,再遍历字段拿到每个字段的resolve属性,这就是自动生成的Resolver函数。

代码示例

const { Neo4jGraphQL } = require("@neo4j/graphql");
const neo4j = require("neo4j-driver");

// 定义你的类型
const typeDefs = `
  type User {
    id: ID!
    name: String!
  }

  type Query {
    users: [User!]!
  }

  type Mutation {
    createUser(name: String!): User!
  }
`;

// 创建Neo4j驱动和Schema实例
const driver = neo4j.driver("bolt://localhost:7687", neo4j.auth.basic("neo4j", "password"));
const neoSchema = new Neo4jGraphQL({ typeDefs, driver });

// 获取最终的GraphQLSchema
const schema = await neoSchema.getSchema();

// 提取Query类型的所有Resolvers
const queryType = schema.getQueryType();
const queryResolvers = {};
for (const [fieldName, fieldConfig] of Object.entries(queryType.getFields())) {
  queryResolvers[fieldName] = fieldConfig.resolve;
}

// 提取Mutation类型的所有Resolvers
const mutationType = schema.getMutationType();
const mutationResolvers = {};
for (const [fieldName, fieldConfig] of Object.entries(mutationType.getFields())) {
  mutationResolvers[fieldName] = fieldConfig.resolve;
}

// 打印结果,就能看到对应的Resolver函数
console.log("Query Resolvers:", queryResolvers);
console.log("Mutation Resolvers:", mutationResolvers);

注意事项

  • 自动生成的Resolver依赖Neo4j驱动上下文,直接调用这些函数时,需要传入包含driver或neo4jDatabase的上下文参数,否则会报错。
  • 不要依赖Neo4jGraphQL实例的内部私有属性(比如neoSchema.schemaBuilder.resolvers),这些属于未公开的实现细节,版本更新后可能会被修改,导致代码失效。
  • 如果你合并了自定义Resolver,这种方法也能提取到合并后的完整Resolver集合。

内容的提问来源于stack exchange,提问作者code-withAshish

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:47:14