npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

token-dealer

v3.0.0

Published

Circumvent API rate limits by having several API tokens and let the dealer manage and give them to you

Downloads

92

Readme

token-dealer

NPM version Downloads Build Status Coverage Status Dependency status Dev Dependency status Greenkeeper badge

Circumvent API rate limits by having several API tokens and let the dealer manage and give them to you.

Several public APIs, such as GitHub and Twitter, have rate limits applied per account. To multiply these rate limits, you must have a farm of tokens associated to multiple accounts, either donated or created by you. This is where token-dealer comes in, making it easy to manage these tokens and their usage.

Installation

$ npm install token-dealer

Usage

tokenDealer(tokens, fn, [options])

Calls fn(token, exhaust) with the most appropriate token from tokens and a exhaust function that you may call to signal that the token is exhausted.

Basically the only thing you must do is call exhaust(reset, [retry]) whenever you know that the token may not be used again until reset (timestamp in ms). Additionally, you may retry if the operation you were trying to do failed because the token was exhausted, causing fn to be called again with another token.

Here's an example from a request to the GitHub API using got:

const tokenDealer = require('tokenDealer');
const got = require('got');

const tokens = [
    'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
    'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
];

tokenDealer(tokens, (token, exhaust) => {
    const handleRateLimit = (response, err) => {
        if (response.headers['x-ratelimit-remaining'] === '0') {
            const isRateLimitError = err && err.statusCode === 403 && /rate limit/i.test(response.body.message);

            exhaust(Number(response.headers['x-ratelimit-reset']) * 1000, isRateLimitError);
        }
    };

    return got('https://api.github.com/repos/moxystudio/node-cross-spawn', {
        json: true,
        headers: { Authorization: `token ${token}` },
    })
    .then((response) => {
        handleRateLimit(response);
        return response;
    }, (err) => {
        err.response && handleRateLimit(err.response, err);
        throw err;
    });
})
.then((response) => {
    // ...
}, (err) => {
    // If all tokens are exhausted, err.code will be 'EALLTOKENSEXHAUSTED'
});

Available options:

  • group: The group associated to the tokens; this effectively groups tokens to prevent conflicts (e.g. github, defaults to default).
  • wait: True to wait for a token to be free in case all are exhausted (defaults to false); alternatively you may pass a function that will be called with [token, duration] so that you can decide to wait dynamically.
  • lru: A custom LRU cache instance to be used internally.
  • onExhausted: Called with (token, reset) whenever a token become exhausted (defaults to null).

If tokens is nullish or an empty array, the given token will be an empty string.

tokenDealer.getTokensUsage(tokens, [options])

Get the tokens usage for tokens. The available options are group and lru which are the same as tokenDealer().

const tokenDealer = require('tokenDealer');

const tokens = [
    'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
    'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
];

const usage = tokenDealer.getTokensUsage(tokens);

// `usage` looks like this:
// {
//     'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa': {
//         exhausted: true,       // true if exhausted, false otherwise
//         reset: 1455996883369,  // the timestamp in which the token will become available again
//         inflight: 0,           // the number of deliveries (`fn` calls) that still haven't completed
//     },
//     'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb': {
//         // ...
//     }
// }

Tests

$ npm test
$ npm test -- --watch during development

License

Released under the MIT License.