rest - 如何使用apollo客户端发出休息后请求?

标签 rest apollo apollo-client react-apollo apollo-server

我知道我们也可以使用 apollo 执行休息请求,但我不知道如何执行发布请求,有人可以帮助我吗?

我的 REST post 请求端点是:<url>/transaction/getbyhash

有效负载:

{"hash":"4e23f9e1d1729996de46fc94d28475b4614f101d72a98f221493f900dc33e0c2"}

有人可以帮我使用 apollo 客户端和 graphql-tag 编写相同的请求吗?

最佳答案

您可以使用apollo-link-rest在 GraphQL 查询中调用 REST API。

例如

rest-api-server.ts:

import express from 'express';
import faker from 'faker';

const app = express();
const port = 3000;

app.use(express.json());
app.post('/api/transaction/getbyhash', (req, res) => {
  console.log(req.body);
  res.json({
    email: faker.internet.email(),
    name: faker.name.findName(),
  });
});

app.listen(port, () => console.log(`HTTP server is listening on http://localhost:${port}`));

client.ts:

import { ApolloClient } from 'apollo-client';
import { RestLink } from 'apollo-link-rest';
import { InMemoryCache } from 'apollo-cache-inmemory';
import gql from 'graphql-tag';
import fetch from 'isomorphic-fetch';

const restLink = new RestLink({
  uri: 'http://localhost:3000/api/',
  customFetch: fetch,
  headers: {
    'Content-Type': 'application/json',
  },
});

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: restLink,
});

const getbyhashQuery = gql`
  fragment Payload on REST {
    hash: String
  }
  query Me($input: Payload!) {
    person(input: $input) @rest(type: "Person", method: "POST", path: "transaction/getbyhash") {
      email
      name
    }
  }
`;
const payload = { hash: '4e23f9e1d1729996de46fc94d28475b4614f101d72a98f221493f900dc33e0c2' };

client.query({ query: getbyhashQuery, variables: { input: payload } }).then((res) => {
  console.log(res.data);
});

日志:

{
  person: {
    email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="df9dada6bcbaeceb9fb8b2beb6b3f1bcb0b2" rel="noreferrer noopener nofollow">[email protected]</a>',
    name: 'Miss Jaren Senger',
    __typename: 'Person'
  }
}

软件包版本:

"apollo-cache-inmemory": "^1.6.6",
"apollo-client": "^2.6.10",
"apollo-link": "^1.2.14",
"apollo-link-rest": "^0.7.3",
"graphql-anywhere": "^4.2.7",
"graphql": "^14.6.0",
"isomorphic-fetch": "^3.0.0",

关于rest - 如何使用apollo客户端发出休息后请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67860366/

相关文章:

node.js - 在 Node js + Express 中放置中间件

c# - 现在 WebServiceHost2Factory 已死,我如何从 WCF 休息服务返回错误文本?

error-handling - 如何消耗 Vue Graphql 组件中的错误并让其他错误全局处理?

javascript - 如何使用 Apollo 2 使用 GraphQL 查询中的数据预填写表单?

Next.js 在 getServerSideProps 中使用 apollo 客户端缓存

reactjs - 使用 fetchMore 获取组件挂载上的所有数据

javascript - 面向公众的 REST 身份验证机制

java - 如何从 json rest 服务器答案中检索字段?

javascript - React、Apollo 2、GraphQL、身份验证。如何在登录后重新渲染组件

node.js - 无法从 apollo-client 导入 createBatchingNetworkInterface