Я пытаюсь создать простое модульное приложение Node.js с использованием GraphQL, чтобы немного его изучить. Я реализовал несколько типов и без особого успеха попытался поиграть с ними в 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;
Server.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.info(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.info('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"
}
}
}