1.0.0 • Published 5 years ago

keyro v1.0.0

Weekly downloads
1
License
MIT
Repository
-
Last release
5 years ago

keyro - key rotation utility

Build Status Codacy Badge Codacy GitHub code size in bytes GitHub All Releases GitHub

What is this

Keyro is just a simple utility to store an array of values and return the 'next one' on every 'get' access.

I have done it to mitigate the rate limit overload on some services, so a different key is used on every request, but as it is something very generic I guess it can be useful on other situations.

Requirements

This is a npm package, and you will need a node version which supports ES6. Anyway, the code is really simple, and could be reduced to drop node dependencies so it can be used also on browsers:

class Keyro {
  constructor({ pool = [] } = {}) {
    if (!Array.isArray(pool)) {
      throw new Error("pool has to be an array");
    }

    this.pointer = 0;
    this.pool = pool;
  }

  add(key) {
    this.pool = [...this.pool, key];
  }

  get() {
    const value = this.pool[this.pointer];
    const hasReachTheEnd = this.pointer >= this.pool.length - 1;
    const nextPointerValue = hasReachTheEnd ? 0 : this.pointer + 1;
    this.pointer = nextPointerValue;
    return value;
  }
}

Installation

npm i --save keyro

Usage

const Keyro = require("keyro");

const keysFromConfig = [
  "SDF9DF897SFGD98A7SDF",
  "VB8N8SC7G68DF8B76S4D",
  "OOLI4L2L1U5I3HJU5K15"
];

const keyro = new Keyro({ pool: keysFromConfig });

function getApiKey() {
  return keyro.get();
}

console.log(getApiKey()); // "SDF9DF897SFGD98A7SDF"
console.log(getApiKey()); // "VB8N8SC7G68DF8B76S4D"
console.log(getApiKey()); // "OOLI4L2L1U5I3HJU5K15"
console.log(getApiKey()); // "SDF9DF897SFGD98A7SDF"
console.log(getApiKey()); // "VB8N8SC7G68DF8B76S4D"
console.log(getApiKey()); // "OOLI4L2L1U5I3HJU5K15"