Code Monkey home page Code Monkey logo

gh-got's Introduction

gh-got

Convenience wrapper for Got to interact with the GitHub API

Unless you're already using Got, you should probably use GitHub's own @octokit/rest.js or @octokit/graphql.js packages instead.

Install

npm install gh-got

Usage

Instead of:

import got from 'got';

const token = 'foo';

const {body} = await got('https://api.github.com/users/sindresorhus', {
	json: true,
	headers: {
		'accept': 'application/vnd.github.v3+json',
		'authorization': `token ${token}`
	}
});

console.log(body.login);
//=> 'sindresorhus'

You can do:

import ghGot from 'gh-got';

const {body} = await ghGot('users/sindresorhus', {
	context: {
		token: 'foo'
	}
});

console.log(body.login);
//=> 'sindresorhus'

Or:

import ghGot from 'gh-got';

const {body} = await ghGot('https://api.github.com/users/sindresorhus', {
	context: {
		token: 'foo'
	}
});

console.log(body.login);
//=> 'sindresorhus'

API

Same API as got, including options, the stream API, aliases, pagination, etc, but with some additional options below.

Errors are improved by using the custom GitHub error messages. Doesn't apply to the stream API.

gh-got specific options

token

Type: string

GitHub access token.

Can be set globally with the GITHUB_TOKEN environment variable.

prefixUrl

Type: string
Default: https://api.github.com/

To support GitHub Enterprise.

Can be set globally with the GITHUB_ENDPOINT environment variable.

body

Type: object

Can be specified as a plain object and will be serialized as JSON with the appropriate headers set.

Rate limit

Responses and errors have a .rateLimit property with info about the current rate limit. (This is not yet implemented for the stream API)

import ghGot from 'gh-got';

const {rateLimit} = await ghGot('users/sindresorhus');

console.log(rateLimit);
//=> {limit: 5000, remaining: 4899, reset: [Date 2018-12-31T20:45:20.000Z]}

Authorization

Authorization for GitHub uses the following logic:

  1. If options.headers.authorization is passed to gh-got, then this will be used as first preference.
  2. If options.token is provided, then the authorization header will be set to token <options.token>.
  3. If options.headers.authorization and options.token are not provided, then the authorization header will be set to token <process.env.GITHUB_TOKEN>

In most cases, this means you can simply set GITHUB_TOKEN, but it also allows it to be overridden by setting options.token or options.headers.authorization explicitly. For example, if authenticating as a GitHub App, you could do the following:

import ghGot from 'gh-got';

const options = {
	headers: {
		authorization: `Bearer ${jwt}`
	}
};
const {body} = await ghGot('app', options);

console.log(body.name);
//=> 'MyApp'

Pagination

See the Got docs.

gh-got's People

Contributors

arthurvr avatar dsblv avatar egul avatar floatdrop avatar fregante avatar kevva avatar linusu avatar ntwb avatar rarkins avatar richienb avatar samverschueren avatar sindresorhus avatar szmarczak avatar tadatuta avatar wangsai avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gh-got's Issues

Is creating gists supported?

Tried via

await ghGot(apiUrl, { token: this._token, method: 'post' })

as well as

await ghGot.post(apiUrl, { token: this._token })

but i get a (node:30976) UnhandledPromiseRejectionWarning: HTTPError: Response code 404 (Not Found)

I wonder if i'm being clumsy or that gh-got does not support this part of the api?

Populate error with information from Github

The Github API returns error information in the body as encoded json, it would be nice to get better error messages by using this information.

e.g.

HTTP/1.1 400 Bad Request
Content-Length: 35

{"message":"Problems parsing JSON"}

currently results in:

HTTPError: Response code 400 (Bad Request)

would be nice to get something like:

GithubError: Problems parsing JSON (400)

Promise API

Expose the got promise API. In contrast to got, I think we can just drop the callback interface and go all in on promises here. Help welcome.

Pass in entire GH url as path

The link header returns URLs for the next, previous, last and first pages. I think it would be nice to use them directly in a gh-got call without having to provide an empty endpoint option.

Just a little example:

const linkParse = require('github-link-parse');

function fetch(user, opts, url) {
    return ghGot(url || `/users/${user}/repos`, {token: opts.token})
        .then(res => {
            const links = linkParse(res.headers.link);

            if(links.next) {
                return fetch(user, opts, links.next);
            }
        });
}

We can check if the path starts with http(s) and use that as the entire url instead of as path. Can do a PR if you want.

Release gh-got that's compatible with got@>=11.8.5

The got package in version <11.8.5 has a vulnerability CVE-2022-33987.
The latest released version of gh-got (v9.0.0) depends on got@^10.5.7.

I can see this commit (Jan 1, 2022) bumped the dependency to got@^12. But since then, the package gh-got was not released. So this change is not available to the users of gh-got package.

Would you mind releasing a new version of gh-got that includes the dependency on got v12?

Serialize body as JSON by default

By default the response is parsed as JSON, but the body parameter is still serialised as x-www-urlencoded which Github doesn't support. I think it would be nice if it could serialise to JSON by default.

GHE envvar overrides normal usage

I occasionally use gh-got as a dep for both github.com and GHE apis. I have an env var, GITHUB_ENDPOINT, for the latter. However, this code:

endpoint: env.GITHUB_ENDPOINT ? env.GITHUB_ENDPOINT.replace(/[^/]$/, '$&/') : 'https://api.github.com/'

Assumes that I am always using it. This breaks some use cases. I could look up and install directory based environment managers, but I am wondering if an easier fix would be to ensure that this setting is only called when you send an opt in. Right now, there isn't even an option for that.

How would you deal with this?

silent or mute option?

this passing noop function to got is weird and okey I understand why is it, but break some things sometimes. I think better would be to have silent or mute option and pass it if you dont want to catch the things.

Remove leading slash in URL parameter

gh-got/index.js

Lines 38 to 42 in 6c0fe96

// TODO: This should be fixed in Got
// TODO: This doesn't seem to have any effect.
if (typeof options.url === 'string' && options.url.startsWith('/')) {
options.url = options.url.slice(1);
}

It will need to be fixed in Got.

Reversing priority of token and endpoint environment variables

Started as a line comment but let's make it an issue and fix/close it.

The readme says clearly:

Can be overridden globally with the GITHUB_TOKEN environment variable.

Same for the endpoint.

Not sure what the logic was, but I think it would be preferable to use the environment variables only when no applicable argument is passed. An application could have a default token (the env.) but for whatever reason use another token on specific calls.

The module, readme and test would have to be updated. It could be considered a major change since it's reversing its meaning.

Automatic retry when receiving 5xx responses

I am a heavy user of gh-got as part of renovate. A small percentage of request receive a 502 Bad Gateway response and it's pretty obvious that these should be retried somewhere in the stack rather than bailing and stopping all subsequent processing.

I was going to write a wrapper around gh-got to achieve this but then thought I'd open an issue here for discussion first as it seems like something all users of gh-got would benefit from and not specific to my application.

Relevant thread there: sindresorhus/got#199 (kind of dismissing the idea).

Additionally: I do not need stream support

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.