GraphQL返回null

时间:2018-10-15 12:45:40

标签: node.js graphql graphiql

我正在尝试使用GraphQL创建一个简单的模块化Node.js应用程序,以对其进行一些了解。我实现了几种类型,并尝试在GraphiQL中使用它们,但没有取得太大的成功。这是一个最小的 non 工作示例。 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);
});

在GraphiQL中,如果我打电话给{hello},我会正确地看到结果{data:hello:“ ciao”}},但是当我尝试以下操作时:

{
  mdc {
    getAll
  }
}

结果为空:

{
  "data": {
    "mdc": null
  }
}

我真的不明白怎么了。我认为这可能与查询类型的定义方式有关(主要是因为我不了解其目的),但也许我在其他地方有问题。

谢谢!

1 个答案:

答案 0 :(得分:1)

我的意思是,核心:

// 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"
        }
    }
 }