如何使用Apollo服务器从变量运行graphql查询

时间:2018-12-28 10:15:07

标签: graphql apollo-server

使用纯graphql实现,我们可以从字符串中运行查询,如下所示:

var { graphql, buildSchema } = require('graphql');

var schema = buildSchema(`
  type Query {
    hello: String
  }
`);

var root = { hello: () => 'Hello world!' };

graphql(schema, '{ hello }', root).then((response) => {
  console.log(response);
});

但是在ApolloServer中找不到相同的方法:

const server = new ApolloServer({ typeDefs, resolvers });
// something like this
server.runQuery('{ hello }');

1 个答案:

答案 0 :(得分:4)

实际上,您可以像这样测试查询:

const { ApolloServer, gql } = require('apollo-server');
const { createTestClient } = require('apollo-server-testing');

const typeDefs = gql`
  type Query {
    hello: String
  }
`;

const resolvers = {
  Query: {
    hello: () => 'Hello world!'
  }
};

const server = new ApolloServer({ typeDefs, resolvers });
const { query } = createTestClient(server);
const res = query({ query: '{ hello }' });
res.then(({ data }) => console.log(data))
// ==> [Object: null prototype] { hello: 'Hello world!' }