【问题标题】:Is any library of nodejs work with GitHub API v4 exist?是否存在任何与 GitHub API v4 一起使用的 nodejs 库?
【发布时间】:2020-06-12 00:03:54
【问题描述】:

谢谢你们阅读我的问题。标题正是我想知道的。 希望它不会花费您太多时间。

【问题讨论】:

标签: node.js graphql github-api


【解决方案1】:

一些最常见的 graphql 客户端是 graphql.jsapollo-client。您还可以使用流行的request 模块。 graphql API 是 https://api.github.com/graphql 上的单个 POST 端点,其 JSON 正文由 query 字段和 variables 字段组成(如果查询中有变量)

使用graphql.js

const graphql = require('graphql.js');

var graph = graphql("https://api.github.com/graphql", {
  headers: {
    "Authorization": "Bearer <Your Token>",
    'User-Agent': 'My Application'
  },
  asJSON: true
});

graph(`
    query repo($name: String!, $owner: String!){
        repository(name:$name, owner:$owner){
            createdAt      
        }
    }
`)({
  name: "linux",
  owner: "torvalds"
}).then(function(response) {
  console.log(JSON.stringify(response, null, 2));
}).catch(function(error) {
  console.log(error);
});

使用apollo-client

fetch = require('node-fetch');
const ApolloClient = require('apollo-client').ApolloClient;
const HttpLink = require('apollo-link-http').HttpLink;
const setContext = require('apollo-link-context').setContext;
const InMemoryCache = require('apollo-cache-inmemory').InMemoryCache;
const gql = require('graphql-tag');

const token = "<Your Token>";

const authLink = setContext((_, {
    headers
}) => {
    return {
        headers: {
            ...headers,
            authorization: token ? `Bearer ${token}` : null,
        }
    }
});

const client = new ApolloClient({
    link: authLink.concat(new HttpLink({
        uri: 'https://api.github.com/graphql'
    })),
    cache: new InMemoryCache()
});

client.query({
        query: gql `
    query repo($name: String!, $owner: String!){
        repository(name:$name, owner:$owner){
            createdAt      
        }
    }
  `,
        variables: {
            name: "linux",
            owner: "torvalds"
        }
    })
    .then(resp => console.log(JSON.stringify(resp.data, null, 2)))
    .catch(error => console.error(error));

使用request

const request = require('request');

request({
    method: 'post',
    body: {
        query: `
    query repo($name: String!, $owner: String!){
        repository(name:$name, owner:$owner){
            createdAt      
        }
    } `,
        variables: {
            name: "linux",
            owner: "torvalds"
        }
    },
    json: true,
    url: 'https://api.github.com/graphql',
    headers: {
        Authorization: 'Bearer <Your Token>',
        'User-Agent': 'My Application'
    }
}, function(error, response, body) {
    if (error) {
        console.error(error);
        throw error;
    }
    console.log(JSON.stringify(body, null, 2));
});

【讨论】:

  • 对不起,我是新会员。
猜你喜欢
  • 2020-11-02
  • 1970-01-01
  • 2017-01-13
  • 1970-01-01
  • 2015-07-23
  • 1970-01-01
  • 2018-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多