Apollo GraphQL。从服务器上调用一个突变?[英] Apollo GraphQL: Call a Mutation from the Server?

本文是小编为大家收集整理的关于Apollo GraphQL。从服务器上调用一个突变?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我需要从服务器上运行的cron作业中调用突变. 我找到了这个帖子,但是接受的答案是说没有办法做到.

然后,我在2017年从Github找到了这一点,从2017年开始:

graphql-server是graphql core函数的网络包装器.如果你 不想在网络上使用它,您只能独立运行它:

import scheme from './scheme';

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

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

函数文档可以找到在这里

看起来还不错!这是2020年的最佳实践吗?

推荐答案

我也发现了这种方法.可以直接在服务器上创建Apollo客户端.

export const getApolloServerClient = () =>

  new ApolloClient({

    ssrMode: true,

    cache: new InMemoryCache(),

    link: new SchemaLink({ schema }),

  });

其他推荐答案

是的,如果您可以访问GraphQl Server使用的GraphQLSchema对象,那么最简单的方法就是仅使用 graphql graphql模块导出的函数.请注意,您应该等待返回的承诺访问结果:

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

但是,您还可以通过网络向服务器本身提出请求 - 如果服务器在同一主机上,则只需使用localhost或127.0.0.1.在这种情况下,您可以在node.js脚本中使用axios,request或任何其他HTTP客户端库.您也可以只使用curl直接在bash脚本或curl命令中制作请求.

本文地址:https://www.itbaoku.cn/post/1938041.html

问题描述

I need to call a mutation from a cron job running on the server. I found this SO post, but the accepted answer said there was no way to do it.

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

That looks pretty good! Is that the best practices approach in 2020?

推荐答案

I just found out about this approach as well. It's possible to create an Apollo client directly on the server.

export const getApolloServerClient = () =>

  new ApolloClient({

    ssrMode: true,

    cache: new InMemoryCache(),

    link: new SchemaLink({ schema }),

  });

其他推荐答案

Yes, if you have access to the GraphQLSchema object used by your GraphQL server, then the simplest approach is to just use the graphql function exported by the graphql module. Note that you should await the returned Promise to access the result:

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

However, you can also make requests to the server itself over the network -- if the server is on the same host, you'd just use localhost or 127.0.0.1. In that case, you can use axios, request or any other HTTP client library in a Node.js script. You can also just use curl to make the request directly in a bash script or curl command.