[GraphQL] Query a GraphQL API with graphql-request
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[GraphQL] Query a GraphQL API with graphql-request相关的知识,希望对你有一定的参考价值。
To query a GraphQL API, all you need to do is send an HTTP request that includes the query operation in the body of the request. In this lesson, we will use the browser’s fetch method to request the total days skied from our GraphQL API.
const query = ` query { totalDays } `; console.log("querying the count"); fetch("https://8lq1n313m2.sse.codesandbox.io", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query }) }) .then(res => res.json()) .then(({ data }) => `totalDays: ${data.totalDays}`) .then(console.log) .catch(console.error);
graphql-request is a lightweight package that can be used to send queries to any GraphQL API. Sending a request with graphql-request uses less syntax than a fetch request. In this lesson, we will query the totalDays field using this helper package.
Install:
npm i --save graphql-request
import { request } from "graphql-request"; const query = ` query { totalDays } `; console.log("querying the count"); request("https://8lq1n313m2.sse.codesandbox.io", query) .then(({ totalDays }) => `totalDays: ${totalDays}`) .then(console.log) .catch(console.error);
Source: https://github.com/prisma/graphql-request
Personally, I feel you can do some wrapper for raw fetch function by yourself instead of install a new dependency to your project, it add more bytes to the total bundles but in return, it is shorten your own code.
以上是关于[GraphQL] Query a GraphQL API with graphql-request的主要内容,如果未能解决你的问题,请参考以下文章
[GraphQL] Query GraphQL Interface Types in GraphQL Playground
如何在 .graphql 文件中编写 GraphQl Upsert Query
[GraphQL] Reuse Query Fields with GraphQL Fragments
[GraphQL] Filter Data Based on Query Arguments with GraphQL
[React + GraphQL] Use useLazyQuery to manually execute a query with Apollo React Hooks
<Query> vs graphql Hoc,这是在 react apollo 中将 graphql 查询与组件挂钩的最佳方法