zoukankan      html  css  js  c++  java
  • [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. 

  • 相关阅读:
    树莓派3 之 启动 和 系统配置
    树莓派3 之 初次使用
    Python 资源大全中文版
    乔布斯:遗失的访谈
    CSS3j背景渐变,字体颜色渐变,以及兼容IE写法
    系统设计相关
    JSON格式要求
    VUE解决空格和空行报错的问题
    css3实现悬停波浪效果
    css3实现匀速无限滚动效果
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10234912.html
Copyright © 2011-2022 走看看