• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

pksunkara/octonode: github api v3 in nodejs

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

pksunkara/octonode

开源软件地址:

https://github.com/pksunkara/octonode

开源编程语言:

CoffeeScript 93.3%

开源软件介绍:

octonode

octonode is a library for nodejs to access the github v3 api

Installation

npm install octonode

Usage

var github = require('octonode');

// Then we instantiate a client with or without a token (as show in a later section)

var ghme           = client.me();
var ghuser         = client.user('pksunkara');
var ghrepo         = client.repo('pksunkara/hub');
var ghorg          = client.org('flatiron');
var ghissue        = client.issue('pksunkara/hub', 37);
var ghmilestone    = client.milestone('pksunkara/hub', 37);
var ghlabel        = client.label('pksunkara/hub', 'todo');
var ghpr           = client.pr('pksunkara/hub', 37);
var ghrelease      = client.release('pksunkara/hub', 37);
var ghgist         = client.gist();
var ghteam         = client.team(37);
var ghproject      = client.project(37);
var ghnotification = client.notification(37);

var ghsearch = client.search();

Build a client which accesses any public information

var client = github.client();

client.get('/users/pksunkara', {}, function (err, status, body, headers) {
  console.log(body); //json object
});

Build a client from an access token

var client = github.client('some_access_token');

client.get('/user', {}, function (err, status, body, headers) {
  console.log(body); //json object
});

Build a client from a different host

You can configure the protocol, hostname and port to use. For example to connect to a GitHub Enterprise instance.

var client = github.client('some_access_token', {
  hostname: 'mydomain.com/api/v3'
});

client.get('/user', {}, function (err, status, body, headers) {
  console.log(body); //json object
});

Request Options

Request options can be set by setting defaults on the client. (e.g. Proxies)

var client = github.client();

client.requestDefaults['proxy'] = 'https://myproxy.com:1085'

These options are passed through to request, see their API here: https://github.com/request/request#requestoptions-callback

Proxies

You can set proxies dynamically by using the example above, but Octonode will respect environment proxies by default. Just set this using: export HTTP_PROXY='https://myproxy.com:1085' if you are using the command line

Many of the below use cases use parts of the above code

Conditional requests

The client supports conditional requests and helps you respecting rate limits by caching information that hasn't changed. You can add the If-None-Match header to each request calling the conditional method.

var client = github.client();

// This add If-None-Match header to the request
github.repo().conditional('ETAG').issues();

More info about conditional requests can be founded here.

Authentication

Authenticate to github in cli mode (desktop application)

Note: Ensure that the scopes argument is an object containing the required note property. For two-factor authentication add the One Time Password otp key with its corresponding code to the configuration object.

var scopes = {
  'scopes': ['user', 'repo', 'gist'],
  'note': 'admin script'
};

github.auth.config({
  username: 'pksunkara',
  password: 'password'
}).login(scopes, function (err, id, token, headers) {
  console.log(id, token);
});

Authenticate to github in web mode (web application)

// Web application which authenticates to github
var http = require('http')
  , url = require('url')
  , qs = require('querystring')
  , github = require('octonode');

// Build the authorization config and url
var auth_url = github.auth.config({
  id: 'mygithubclientid',
  secret: 'mygithubclientsecret',
  apiUrl: 'https://optional-internal-github-enterprise/api/v3',
  webUrl: 'https://optional-internal-github-enterprise'
}).login(['user', 'repo', 'gist']);

// Store info to verify against CSRF
var state = auth_url.match(/&state=([0-9a-z]{32})/i);

// Web server
http.createServer(function (req, res) {
  uri = url.parse(req.url);
  // Redirect to github login
  if (uri.pathname=='/login') {
    res.writeHead(302, {'Content-Type': 'text/plain', 'Location': auth_url})
    res.end('Redirecting to ' + auth_url);
  }
  // Callback url from github login
  else if (uri.pathname=='/auth') {
    var values = qs.parse(uri.query);
    // Check against CSRF attacks
    if (!state || state[1] != values.state) {
      res.writeHead(403, {'Content-Type': 'text/plain'});
      res.end('');
    } else {
      github.auth.login(values.code, function (err, token, headers) {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end(token);
      });
    }
  } else {
    res.writeHead(200, {'Content-Type': 'text/plain'})
    res.end('');
  }
}).listen(3000);

console.log('Server started on 3000');

Rate Limiting

You can also check your rate limit status by calling the following.

client.limit(function (err, left, max, reset) {
  console.log(left); // 4999
  console.log(max);  // 5000
  console.log(reset);  // 1372700873 (UTC epoch seconds)
});

API Callback Structure

All the callbacks for the following will take first an error argument, then a data argument, like this:

ghme.info(function(err, data, headers) {
  console.log("error: " + err);
  console.log("data: " + data);
  console.log("headers:" + headers);
});

Async / Promises

If you would like to work with promises rather than callbacks, you can call the promise based version of any of the api calls by appending Async to the function call.

For example prs() becomes prsAsync() like this:

async function getPullRequests () {
  const client = github.client(config.githubAccessToken)
  const repo = client.repo('pksunkara/octonode')

  const result = await repo.prsAsync({ per_page: 100 })
  return result[0]
}

Pagination

If a function is said to be supporting pagination, then that function can be used in many ways as shown below. Results from the function are arranged in pages.

The page argument is optional and is used to specify which page of issues to retrieve. The perPage argument is also optional and is used to specify how many issues per page.

// Normal usage of function
ghrepo.issues(callback); //array of first 30 issues

// Using pagination parameters
ghrepo.issues(2, 100, callback); //array of second 100 issues
ghrepo.issues(10, callback); //array of 30 issues from page 10

// Pagination parameters can be set with query object too
ghrepo.issues({
  page: 2,
  per_page: 100,
  state: 'closed'
}, callback); //array of second 100 issues which are closed

Github authenticated user api

Token/Credentials required for the following:

Get information about the user (GET /user)

ghme.info(callback); //json

Update user profile (PATCH /user)

ghme.update({
  "name": "monalisa octocat",
  "email": "[email protected]",
}, callback);

Get emails of the user (GET /user/emails)

ghme.emails(callback); //array of emails

Set emails of the user (POST /user/emails)

ghme.emails(['[email protected]', '[email protected]'], callback); //array of emails
ghme.emails('[email protected]', callback); //array of emails

Delete emails of the user (DELETE /user/emails)

ghme.emails(['[email protected]', '[email protected]']);
ghme.emails('[email protected]');

Get the followers of the user (GET /user/followers)

ghme.followers(callback); //array of github users

Get users whom the user is following (GET /user/following)

This query supports pagination.

ghme.following(callback); //array of github users

Check if the user is following a user (GET /user/following/marak)

ghme.following('marak', callback); //boolean

Follow a user (PUT /user/following/marak)

ghme.follow('marak');

Unfollow a user (DELETE /user/following/marak)

ghme.unfollow('marak');

Get public keys of a user (GET /user/keys)

ghme.keys(callback); //array of keys

Get a single public key (GET /user/keys/1)

ghme.keys(1, callback); //key

Create a public key (POST /user/keys)

ghme.keys({"title":"laptop", "key":"ssh-rsa AAA..."}, callback); //key

Update a public key (PATCH /user/keys/1)

ghme< 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap