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

标签 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 }');

最佳答案

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

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

关于graphql - 如何使用 apollo 服务器从变量运行 graphql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53956859/

相关文章:

spring - 带有 graphql-spring 的 LazyInitializationException

api - 如何使用 GitHub GraphQL API 获取具有特定主题的所有存储库?

file-upload - 如何在 Jest 中模拟文件上传或文件对象?

Meteor/React/ApolloServer/BodyParser - 有效负载太大

graphql - Apollo Server 2 + Express : req. 后处理程序缺少正文

graphql - 从变体图像中获取多个transformedSrc

java - 将多个 graphQL 模式文件映射到单独的解析器 - Spring Boot

node.js - Graphql - Apollo 服务器 - 热更新模式

node.js - 使用 ApolloClient 和 Apollo-Server-Express 进行 GraphQL 错误处理

javascript - Apollo Express GraphQL 中出现错误 : Error: Schema must contain uniquely named types but contains multiple types named "DateTime"