NodeJs 中的 GraphQl - 对象类型的解析器



我刚刚开始使用NodeJs中的GraphQl。我了解类型的解析器的位置,如以下示例中的编码所示。

但是我无法弄清楚关系类型的解析器在哪里。 例如,下面的Type Book有一个属性作者,如果查询到,它应该返回作者类型。我在哪里放置解析器来解析本书的作者?

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`  
  type Book {
      id: ID!
      name: String!
      genre: String!
      author: Author
  }
  type Author {
      id: ID!
      name: String!
      age: String!
  }
  type Query {
      books: [Book]
      authors: [Author]
      book(id: ID): Book
      author(id: ID): Author
  }
`);
const root = {
    books: () => {
        return Book.find({});
    },
    authors: () => {
        return Author.find({});
    },
    book:({id}) => {
        return Book.findById(id);
    },
    author:({id}) => {
        return Author.findById(id);
    }
}
const app = express()
app.listen(5000, () =>{
   console.log('listening for request');
})
app.use('/graphql', graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true
}))

您需要为 Book 类型定义特定的解析程序。我建议从 graphql-tools 中获取makeExecutableSchema,这样您就可以轻松构建所需的关系解析器。我已经复制并更改了您的解决方案以达到预期的结果。

const graphqlHTTP = require("express-graphql")
const express = require("express");
const { makeExecutableSchema } = require("graphql-tools")
const typeDefs = `  
  type Book {
      id: ID!
      name: String!
      genre: String!
      author: Author
  }
  type Author {
      id: ID!
      name: String!
      age: String!
  }
  type Query {
      books: [Book]
      authors: [Author]
      book(id: ID): Book
      author(id: ID): Author
  }
`;
const resolvers = {
    Book: {
        author: (rootValue, args) => {
            // rootValue is a resolved Book type.
            return {
                id: "id",
                name: "dan",
                age: "20"
            }
        }
    },
    Query: {
        books: (rootValue, args) => {
            return [{ id: "id", name: "name", genre: "shshjs" }];
        },
        authors: (rootValue, args) => {
            return Author.find({});
        },
        book: (rootValue, { id }) => {
            return Book.findById(id);
        },
        author: (rootValue, { id }) => {
            return Author.findById(id);
        }
    }
}
const app = express();
app.listen(5000, () => {
    console.log('listening for request');
})
app.use('/graphql', graphqlHTTP({
    schema: makeExecutableSchema({ typeDefs, resolvers }),
    graphiql: true
}))

最新更新