【问题标题】:GraphQl in NodeJs - Resolver for Object TypesNodeJs 中的 GraphQl - 对象类型的解析器
【发布时间】:2020-03-17 12:07:18
【问题描述】:

我刚刚开始在 NodeJs 中使用 GraphQl。我了解类型的解析器在下面的示例中编码。

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

// 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
}))

【问题讨论】:

标签: node.js express graphql


【解决方案1】:

您需要为 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
}))

【讨论】:

    猜你喜欢
    • 2020-07-21
    • 2018-04-07
    • 2021-01-23
    • 2019-09-07
    • 2017-08-13
    • 2020-10-04
    • 2018-04-17
    • 2017-02-14
    • 2018-08-27
    相关资源
    最近更新 更多