是否存在任何与GitHub API v4兼容的nodejs库?

时间:2018-06-29 09:09:48

标签: node.js graphql github-api

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

1 个答案:

答案 0 :(得分:3)

一些最常见的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));
});