I am trying to make a simple modularized Node.js application using GraphQL to learn it a little bit. I implemented a couple of types and tried to play with them in the GraphiQL without much success. Here is a minimal non-working example. 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.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);
});
When in GraphiQL, if I call { hello } I correctly see as result { data : hello: "ciao"} } but when I try the following:
{
mdc {
getAll
}
}
The result is null:
{
"data": {
"mdc": null
}
}
I really do not understand what is wrong. I think it may be something related with how the type Query is defined (mostly because I do not understand its purpose) but maybe I have something wrong somewhere else.
Thank you!!
I thing, that is corect:
// 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"
}
};
When you call
{
mdc {
getAll
}
}
answer is
{
"data": {
"mdc": {
"getAll": "get all called"
}
}
}