我正在尝试使用 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 类型的定义方式有关(主要是因为我不明白它的目的)但也许我在其他地方有问题。
谢谢!!