微信小程序中如何使用GraphQL-微信小程序GraphQL客户端-wxapp-graphql

发布于 5 年前 作者 gougou168 1837 次浏览 来自 分享

GraphQL 既是一种用于 API 的查询语言也是一个满足你数据查询的运行时。 GraphQL 对你的 API 中的数据提供了一套易于理解的完整描述,使得客户端能够准确地获得它需要的数据,而且没有任何冗余,也让 API 更容易地随着时间推移而演进,还能用于构建强大的开发者工具。

我们想在微信小程序中使用GraphQL,如何使用呢,下面推荐一款工具wxapp-graphql

wxapp-graphql工具下载地址: github: https://github.com/Authing/wxapp-graphql

微信小程序 GraphQL 客户端,点击图片观看演示 demo

1.png

wxapp-graphql的使用方法

1、’clone 项目 git clone https://github.com/Authing/wxapp-graphql

2、将文件中的 graphql 文件夹复制到你的项目中并开始使用


// 引入文件
var gql = require('path/to/graphql/wxgql.js');
var GraphQL = gql.GraphQL;

Page({
  test: function() {

    // 初始化对象
    let gql = GraphQL({
      url: 'https://users.authing.cn/graphql' // url 必填 
    }, true); //第二个参数的 true 代表是否使用对象方法,如 gql.query 或 gql.mutate,默认是函数方法,如 gql({body: {query: '', variables: {}}}),建议写 true,为 true 时可以使用 promise

    gql.query({
        query: `query getAccessTokenByAppSecret($secret: String!, $clientId: String!){
    getAccessTokenByAppSecret(secret: $secret, clientId: $clientId)
}`,
        variables: {
          secret: '427e24d3b7e289ae9469ab6724dc7ff0',
          clientId: '5a9fa26cf8635a000185528c'
        }
    }).then(function(res) {
      //成功
    }).catch(function(error) {
      //失败
    });
    
  }
});

3、 另外一种使用方法(可选)

var gql = require('path/to/graphql/wxgql.js');
var GraphQL = gql.GraphQL;
Page({
  test: function() {
    let gql = GraphQL({
      url: 'https://users.authing.cn/graphql' // url 必填 
    });
    
    gql({
      // 示例 GraphQL 查询, body 必填
      body: {
        query: `query getAccessTokenByAppSecret($secret: String!, $clientId: String!){
    getAccessTokenByAppSecret(secret: $secret, clientId: $clientId)
}`,
        variables: {
          secret: '427e24d3b7e289ae9469ab6724dc7ff0',
          clientId: '5a9fa26cf8635a000185528c'
        }
      },

      // 成功
      success: function (res) {
        console.log(res);
      },

      // 失败
      fail: function (res) {
        console.log(res);
      },

      // 执行完成
      complete: function (res) {
        console.log(res);
      }
    });
});

1 回复
回到顶部