Apollo GraphQL:从服务器调用突变?

Apollo GraphQL: Call a Mutation from the Server?

我需要从服务器上的 cron 作业 运行 调用变更。 ,但是采纳的回答说没办法。

Then I found this on GitHub, from 2017:

graphql-server is a network wrapper for graphql core function. if you don't want to use it over network, you can just run it standalone:

import scheme from './scheme';

const query = `{
  me {
    name   
  }
}`;

const result = graphql(scheme, query);
console.log(result); 

function documentation can be found here

看起来不错!这是 2020 年的最佳做法吗?

是的,如果您有权访问 GraphQL 服务器使用的 GraphQLSchema 对象,那么最简单的方法就是使用 graphql 模块导出的 graphql 函数。请注意,您应该等待返回的 Promise 才能访问结果:

async function run () {
  const { data, errors } = await graphql(
    schema, 
    query,
    rootValue,
    context,
    variables
  )
}

但是,您也可以通过网络向服务器本身发出请求——如果服务器在同一台主机上,您只需使用 localhost127.0.0.1。在这种情况下,您可以在 Node.js 脚本中使用 axiosrequest 或任何其他 HTTP 客户端库。您也可以只使用 curl 直接在 bash 脚本或 curl 命令中发出请求。

我也刚知道这种方法。可以直接在服务器上创建 Apollo 客户端。

export const getApolloServerClient = () =>

  new ApolloClient({

    ssrMode: true,

    cache: new InMemoryCache(),

    link: new SchemaLink({ schema }),

  });