1.0.3 • Published 4 years ago

@amatsagu/tokenator v1.0.3

Weekly downloads
-
License
ISC
Repository
github
Last release
4 years ago

What is this?

Tokenator is a simple tool that helps dealing with rate limit mechanisms. It uses simple token system to make sure your api will never die under high usage.

Installation

npm install @amatsagu/tokenator

Example usage

Assume we have a function that is resource hungry, let's say it renders new images (dynamically, all the time). By default Node apps uses only 1 core so this function can quickly use entire CPU on your machine.

import Tokenator from '@amatsagu/tokenator'
import { renderImage } from '../my-functions'
import imaginaryData from '../data.json'

// Create new tokenator with max 4 tokens.
const manager = new Tokenator(4)

let progressIndex = 0

async function watchProduction() {

    // Check every 500ms (200ms default) if there's free token.
    await manager.waitForToken(500)


    // Lock 1 (out of 4 in total) token.
    manager.useToken()

    await renderImage(imaginaryData[progressIndex])
    progressIndex++

    // Give token back to pool.
    manager.releaseToken()
}

It's stupidly easy but horribly effective, thanks by this you can be sure that your app will process max 4 images at the same time, no more!

In-depth

All methods


Tokenator Constructor

PropertyDescriptionOptional?Default value
maxTokensAmount of tokens that can be used.Yes10

Tokenator.tokens - Setter & Getter, use it to view maxTokens param or set new value.

Tokenator.used - Getter, use to view how many tokens are currently in use.

Tokenator#waitForToken

Waits until next token will be available. | Property | Description | Optional? | Default value | |-------------|------------------------------------------------------|-----------|---------------| | refreshRate | How long (in ms) to wait between next status checks. | Yes | 200 |

Tokenator#useToken

Locks single token. Returns true on success and false when there's no tokens in pool.

Tokenator#useShadowToken

Locks single token by a set amount of time. Shadow tokens cannot be released manually. Returns true on success and false when there's no tokens in pool. | Property | Description | Optional? | Default value | |------------|-------------------------------------------|-----------|---------------| | borrowTime | How long (in ms) should token be blocked. | No | |

Tokenator#releaseToken

Unlocks single token. Returns true on success and false all tokens were already free.

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago