Yuri Taratorkin
Yuri Taratorkin

Reputation: 647

How to run graphql query with apollo server from variable

With pure graphql implementation we can run query from string like this:

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);
});

But can't find same method in ApolloServer:

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

Upvotes: 2

Views: 528

Answers (1)

xwlee
xwlee

Reputation: 1099

Actually, you can test the query like this:

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!' }

Upvotes: 5

Related Questions