首页 > Windows开发 > 详细

[GraphQL] Query a GraphQL API with graphql-request

时间:2019-01-07 19:41:29      阅读:162      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/Answer1215/p/10234912.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!