是否可以在不使用 http 的情况下在本地查询我的 运行 apollo graphqlserver?

Is it possible to query my running apollo graphqlserver locally, without using http?

我是 运行 来自 Apollo 的 Graphql 服务器,objective 正在获取一些数据。但是,我在本地需要这些数据——在同一台服务器上。这可能吗,或者是使用 http 查询 Apollo 服务器的唯一方法?

我知道我可以在不使用 GraphQl 的情况下完成此操作,只需访问数据层,但我想从中受益:

我已经有了一个可行的解决方案,我只使用 node-fetch 来查询本地主机,但似乎开销很大。

有可能!

Apollo 为您构建和执行模式,但您也可以自己完成。 这是一个基于 apollo-server-express 包的小例子。我创建模式,然后将其提供给 apollo 服务器。在服务器启动下面看,我也创建了一个查询字符串,然后解析它并在没有 apollo 和没有 http 请求的情况下执行它。

const express = require('express');
const { ApolloServer, gql, makeExecutableSchema } = require('apollo-server-express');
const { parse } = require('graphql/language')
const { execute } = require('graphql')

// Construct a schema, using GraphQL schema language
const typeDefs = gql`
  type Query {
    hello: String
  }
`;

// Provide resolver functions for your schema fields
const resolvers = {
  Query: {
    hello: () => 'Hello world!',
  },
};

const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
})

async function startApolloServer() {

  const server = new ApolloServer({ schema });
  await server.start();

  const app = express();
  server.applyMiddleware({ app });

  await new Promise(resolve => app.listen({ port: 4000 }, resolve));
  console.log(` Server ready at http://localhost:4000${server.graphqlPath}`);
  return { server, app };
}

startApolloServer()

const query = `
  query {
    hello
  }
`

const document = parse(query)

const res = execute({
  schema,
  document,
})

console.log('res no request:', res)

如果你 运行 它,用 npm 安装 apollo-server-expressgraphql 就可以了

要执行,您还可以传递所有请求逻辑:

    execute({
      schema,
      document,
      rootValue: {},
      contextValue: {
        userInfo,
        dbClient,
      },
      variableValues: body.variables,
    }),

如果您想测试您的服务器,它也非常有用。如果您需要订阅,您也可以使用从 graphql 导入的 subscribe 方法。