node.js - GraphQL 返回 null
问题描述
我正在尝试使用 GraphQL 制作一个简单的模块化 Node.js 应用程序来学习它。我实现了几种类型,并尝试在 GraphiQL 中使用它们,但没有取得多大成功。这是一个最小的非工作示例。MDC.js:
//MDC.js
module.exports.typeDef = `
type MDC {
getAll: String
getWithInitials(initials: String): [String]
}
`;
module.exports.resolvers = {
MDC: {
getAll: function() {
return "get all called";
},
getWithInitials: function(initials) {
return "get with initials called with initials = " + initials;
}
}
};
Schemas.js:
//schemas.js
const MDC = require('./mdc').typeDef;
const MDCResolvers = require('./mdc').resolvers;
const Query = `
type Query {
mdc: MDC
hello: String
}
`;
const resolvers = {
Query: {
mdc: function() {
return "mdc called (not sure if this is correct)"
}
},
MDC: {
getAll: MDCResolvers.MDC.getAll,
getInitials: MDCResolvers.MDC.getWithInitials,
},
hello: function() {
return "ciao"
}
};
module.exports.typeDefs = [ MDC, Query ];
module.exports.resolvers = resolvers;
服务器.js:
//server.js
const express = require('express');
const app = express();
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');
const port = 8000;
const schemas = require('./app/schemas/schemas');
require('./app/routes')(app, {});
var fullSchemas = "";
for(var i = 0; i < schemas.typeDefs.length; i ++){
fullSchemas += "," + schemas.typeDefs[i];
}
console.log(schemas.resolvers) //I can see the functions are defined
var schema = buildSchema(fullSchemas);
var root = schemas.resolvers;
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(port, () => {
console.log('We are live on ' + port);
});
在 GraphiQL 中,如果我调用 { hello } 我正确地看到了结果 { data : hello: "ciao"} } 但是当我尝试以下操作时:
{
mdc {
getAll
}
}
结果为空:
{
"data": {
"mdc": null
}
}
我真的不明白出了什么问题。我认为这可能与 Query 类型的定义方式有关(主要是因为我不明白它的目的)但也许我在其他地方有问题。
谢谢!!
解决方案
我的事情,这是正确的:
// schemas.js
const resolvers = {
Query: {
mdc: function() {
return "mdc called (not sure if this is correct)"
}
},
mdc: {
getAll: MDCResolvers.MDC.getAll,
getInitials: MDCResolvers.MDC.getWithInitials,
},
hello: function() {
return "ciao"
}
};
你打电话时
{
mdc {
getAll
}
}
答案是
{
"data": {
"mdc": {
"getAll": "get all called"
}
}
}
推荐阅读
- javascript - 如何在 Input 中设置值并选择
- c++ - 替代获取标准库函数的地址/可能是格式错误的行为
- javascript - 创建一个数组,其中包含对特定数字求和所需的数字
- python - 使用 PIL (python) 将图像数据集加载到内存中会消耗太多内存
- php - 使用 PHP 检查 SSL 证书哈希
- c - scanf("%d/%d/%d) 在 C 中是什么意思?
- flutter - 如何在 Flutter 中访问 GridView 中特定项目的索引?
- javascript - 使用 react redux 探针获取异步数据
- php - 如何解决贪婪的正则表达式
- python-2.7 - 我的 Logger 对象正在发送两条消息而不是一条