Coder Social home page Coder Social logo

curtain's Introduction

Curtain

This library is designed to make a yes/no decision about whether to admit a request or to determine that a request has exceeed a threshold and should be rejected with a HTTP 429 or other relevant HTTP response.


NPM


Usage

(See the /test folder in the project for more examples)

// import the code
const RateLimiter = require('curtain');

// initialize a new rlm instance (only really need one per redis connection)
const rlm = new RateLimiter({
    redis: {
        port: 6379,
        host: '127.0.0.1',
        db: 0
    }
});


 // promise based interface
app.use(function (req, res, next) {

    rlm.limit({

        req: req,
        excludeRoutes: [],
        maxReqsPerPeriod: 10,
        periodMillis: 1000,
        identifier: 'ip'

    }).then(function (data) {

        if (data.rateExceeded) {
            res.status(429).json({error: 'Rate limit exceeded', length: data.length});
        } else {
            next();
        }

    }, function (err) {

        if (!err.curtainError) {  //this error is not from the curtain library, pass it on
            return next(err);
        }

        switch (err.type) {
            case rlm.errors.REDIS_ERROR:
                err.status = 500;
                break;
            case rlm.errors.NO_KEY: // whatever you chose to use as you're request unique identifier, there was a problem finding it
                err.status = 500;
                break;
            case rlm.errors.BAD_ARGUMENTS: //if you have some dynamicism in your project, then maybe you could pass bad args at runtime
                err.status = 500;
                break;
            default:
                throw new Error('Unexpected err via rate limiter:' + err);
        }

        next(err);

    });

});


// middleware based interface
 app.use(rlm.limitMiddleware({
 
     excludeRoutes: [],
     maxReqsPerPeriod: 5,
     periodMillis: 2000,
     identifier: 'ip'
 
 }), function (err, req, res, next) {
 
     if (!err.curtainError) {  //this error is not from the curtain library, pass it on
         console.log('zzzz');
         return next(err);
     }
 
     switch (err.type) {
         case rlm.errors.REDIS_ERROR:
             err.status = 500;
             break;
         case rlm.errors.NO_KEY: // whatever you chose to use as you're request unique identifier, there was a problem finding it
             err.status = 500;
             break;
         case rlm.errors.BAD_ARGUMENTS: //if you have some dynamicism in your project, then maybe you could pass bad args at runtime
             err.status = 500;
             break;
         default:
             throw new Error('Unexpected err via rate limiter XXX:' + typeof (err.stack || err) === 'string' ?
                 (err.stack || err) : util.inspect(err));
     }
 
     next(err);
 
 }, function(req,res,next){
 
     if(req.curtain.rateExceeded){
         res.status(429).json({error: 'Rate limit exceeded'});
     }
     else{
         next();
     }
 
 });
 

you can also pass in an existing Redis client like so:

const RateLimiter = require('curtain');

var rlm = new RateLimiter({
    redis: {
        client: yourClient 
    }
});

Note: This library calls your error handling middleware. When the rate limit is exceeded by the newest request it will call your promixate error handling middleware; this same middleware will also be called if any other types of errors occur. All errors (whether they are Redis errors or rate limit errors) should be handled by you like this:




If you don't use the ip value of req.ip, (which you probably shouldn't) then you need to attach a value to req representing the key to use for that user that is making the request.

That might look like this:

req['foo-bar'] = 'some-unique-request-id-for-your-app';


rlm.limit({

    req: req,
    maxReqsPerPeriod: 150,          // maximum number of requests that are allowed to occur during a window
    periodMillis: 3000,             // the window period in milliseconds
    identifier: 'foo-bar'           // string representing what value to read off the req object
    
})

curtain's People

Contributors

oresoftware avatar the1mills avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

curtain's Issues

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.