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

@bleco/ratelimiter

v1.4.10

Published

A loopback-next rate limiting extension

Downloads

98

Readme

@bleco/ratelimiter

A simple loopback-next extension for rate limiting in loopback applications.

Features

@bleco/ratelimiter using rate-limiter-flexible under the hood. It supports following datasources for rate limiting.

  • Memory
  • Redis
  • MongoDB
  • MySQL
  • Postgres

And it also supports following aggregating algorithms for rate limiting.

  • Union Combine 2 or more limiters to act as single
  • Burst Allow traffic bursts with BurstyRateLimiter implementation easier than with TokenBucket.

Install

npm install @bleco/ratelimiter

Usage

In order to use this component into your LoopBack application, please follow below steps.

  • Add component to application.
this.component(RateLimiterComponent);
  • Minimum configuration required for this component is given below.

Configure the datasource to be used for rate limiting. You can use any of the three datasources mentioned above.

this.bind(RateLimitSecurityBindings.CONFIG).to({
  ds: RedisDataSouece, // or data source binding key
});
  • By default, ratelimiter will be initialized with default options as mentioned here. However, you can override any of the options using the Config Binding. Below is an example of how to do it with the redis datasource, you can also do it with other two datasources similarly.
const rateLimitKeyGen = (req: Request) => {
  const token = (req.headers && req.headers.authorization && req.headers.authorization.replace(/bearer /i, '')) || '';
  return token;
};

// ......

this.bind(RateLimitSecurityBindings.CONFIG).to({
  ds: RedisDataSource,
  points: 60,
  key: rateLimitKeyGen,
});
  • The component exposes a sequence action which can be added to your server sequence class. Adding this will trigger ratelimiter middleware for all the requests passing through.
export class MySequence implements SequenceHandler {
  constructor(
    @inject(SequenceActions.FIND_ROUTE) protected findRoute: FindRoute,
    @inject(SequenceActions.PARSE_PARAMS) protected parseParams: ParseParams,
    @inject(SequenceActions.INVOKE_METHOD) protected invoke: InvokeMethod,
    @inject(SequenceActions.SEND) public send: Send,
    @inject(SequenceActions.REJECT) public reject: Reject,
    @inject(RateLimitSecurityBindings.ACTION)
    protected rateLimitAction: RateLimitAction,
  ) {}

  async handle(context: RequestContext) {
    const requestTime = Date.now();
    try {
      const {request, response} = context;
      const route = this.findRoute(request);
      const args = await this.parseParams(request, route);

      // rate limit Action here
      await this.rateLimitAction(request, response);

      const result = await this.invoke(route, args);
      this.send(response, result);
    } catch (err) {
      // ...
    } finally {
      // ...
    }
  }
}
  • This component also exposes a method decorator for cases where you want tp specify different rate limiting options at API method level. For example, you want to keep hard rate limit for unauthorized API requests and want to keep it softer for other API requests. In this case, the global config will be overwritten by the method decoration. Refer below.
const rateLimitKeyGen = (req: Request) => {
  const token = (req.headers && req.headers.authorization && req.headers.authorization.replace(/bearer /i, '')) || '';
  return token;
};

// .....

class SomeController {
  // ...
  @ratelimit(true, {
    points: 60,
    key: rateLimitKeyGen,
  })
  @patch(`/auth/change-password`, {
    responses: {
      [STATUS_CODE.OK]: {
        description: 'If User password successfully changed.',
      },
      ...ErrorCodes,
    },
    security: [
      {
        [STRATEGY.BEARER]: [],
      },
    ],
  })
  async resetPassword(
    @requestBody({
      content: {
        [CONTENT_TYPE.JSON]: {
          schema: getModelSchemaRef(ResetPassword, {partial: true}),
        },
      },
    })
    req: ResetPassword,
    @param.header.string('Authorization') auth: string,
  ): Promise<User> {
    return this.authService.changepassword(req, auth);
  }
}
  • You can also disable rate limiting for specific API methods using the decorator like below.
class SomeController {
  // ...
  @ratelimit(false)
  @authenticate(STRATEGY.BEARER)
  @authorize(['*'])
  @get('/auth/me', {
    description: ' To get the user details',
    security: [
      {
        [STRATEGY.BEARER]: [],
      },
    ],
    responses: {
      [STATUS_CODE.OK]: {
        description: 'User Object',
        content: {
          [CONTENT_TYPE.JSON]: AuthUser,
        },
      },
      ...ErrorCodes,
    },
  })
  async userDetails(@inject(RestBindings.Http.REQUEST) req: Request): Promise<AuthUser> {
    return this.authService.getme(req.headers.authorization);
  }
}
  • More examples can be found here and here.

Credits

License

MIT