Graphql在Graphql和express中不断返回null



我正在尝试在GraphQL中查询数据并表达。我编写了模式和解析器,但无论我做什么,它总是返回null。我试着重写所有内容,我试着使用apollo express,我到处寻找,但无论我尝试什么,它都不停地返回null。

const express = require("express");
const app = express();
const port = process.env.PORT || 8080;
const { graphqlHTTP } = require("express-graphql");
const { buildSchema } = require("graphql");
const cors = require("cors");
let books = [
{ name: "Name of the Wind", genre: "Fantasy", id: "1", authorId: "1" },
{ name: "The Final Empire", genre: "Fantasy", id: "2", authorId: "2" },
{ name: "The Hero of Ages", genre: "Fantasy", id: "4", authorId: "2" },
{ name: "The Long Earth", genre: "Sci-Fi", id: "3", authorId: "3" },
{ name: "The Colour of Magic", genre: "Fantasy", id: "5", authorId: "3" },
{ name: "The Light Fantastic", genre: "Fantasy", id: "6", authorId: "3" },
];
const Schema = buildSchema(`
type Query {
book(id: ID!): Book!
books: [Book!]
test: String
}
type Book {
id: ID!
name: String!
genre: String!
author: Author!

},
type Author {
id: ID!
name: String!
age: Int!
books: [Book]!
}
`);
let root = {
Query: {
books: () => {
return books;
},
book: (parent: any, args: any) => {
Book.findById(args.id);
},
},
};
app.use(
"/graphql",
cors(),
graphqlHTTP({
schema: Schema, // Must be provided
rootValue: root,
graphiql: true,
})
);

以下是查询:

{
books {
name
id
}
}

这是查询响应:

{
"data": {
"books": null
}
}

希望足够了。

通过排除以下行,我能够让您的查询在apollo服务器中工作。打算将findById应用于书籍吗?

book: (parent: any, args: any) => {
Book.findById(args.id);  
} 

见下文:

const { ApolloServer, gql } = require("apollo-server");
let books = [
{ name: "Name of the Wind", genre: "Fantasy", id: "1", authorId: "1" },
{ name: "The Final Empire", genre: "Fantasy", id: "2", authorId: "2" },
{ name: "The Hero of Ages", genre: "Fantasy", id: "4", authorId: "2" },
{ name: "The Long Earth", genre: "Sci-Fi", id: "3", authorId: "3" },
{ name: "The Colour of Magic", genre: "Fantasy", id: "5", authorId: "3" },
{ name: "The Light Fantastic", genre: "Fantasy", id: "6", authorId: "3" }
];
// Construct a schema, using GraphQL schema language
const typeDefs = gql`
type Query {
book(id: ID!): Book!
books: [Book!]
test: String
}
type Book {
id: ID!
name: String!
genre: String!
author: Author!
}
type Author {
id: ID!
name: String!
age: Int!
books: [Book]!
}
`;
// Provide resolver functions for your schema fields
const resolvers = {
Query: {
books: () => {
return books;
}
}
};
const server = new ApolloServer({
typeDefs,
resolvers
});
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});

需要注意的是:您的图书和图书类型定义不匹配(authorId与author(。

最新更新