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

graphql-rate-limiter

v0.0.8

Published

Rate limiter for graphql resolvers

Downloads

10

Readme


Features

  • 💂‍♀️ Add rate limits to queries or mutations
  • 🤝 Works with any Node.js GraphQL setup (graphql-shield rule and a base rate limiter function for every other use case)
  • 🔑 Add filters to rate limits based on the query or mutation args
  • ❌ Custom error messaging
  • ⏰ Configure using a simple max per window arguments
  • 💼 Custom stores, use Redis, Postgres, Mongo... it defaults to in-memory
  • 💪 Written in TypeScript

Install

npm i graphql-rate-limiter

Examples

Option 1: Using the graphql-shield

import { createRateLimitRule } from "graphql-rate-limit";

// Step 1: get rate limit shield instance rule
const rateLimitRule = createRateLimitRule({
  identifyContext: (ctx) => ctx.id,
});

const permissions = shield({
  Query: {
    // Step 2: Apply the rate limit rule instance to the field with config
    getItems: rateLimitRule({ window: "1s", max: 5 }),
  },
});

const schema = applyMiddleware(
  makeExecutableSchema({
    typeDefs: gql`
      type Query {
        getItems: [Item]
      }
    `,
    resolvers: {
      Query: {
        getItems: () => [{ id: "1" }],
      },
    },
  }),
  permissions
);

Option 2: Using the base rate limiter function

import { getGraphQLRateLimiter } from "graphql-rate-limit";

// Step 1: get rate limit directive instance
const rateLimiter = getGraphQLRateLimiter({
  identifyContext: (ctx) => ctx.id,
});

const schema = makeExecutableSchema({
  typeDefs: `
    type Query {
      getItems: [Item]
    }
  `,
  resolvers: {
    Query: {
      getItems: async (parent, args, context, info) => {
        // Step 2: Apply the rate limit logic instance to the field with config
        const errorMessage = await rateLimiter(
          { parent, args, context, info },
          { max: 5, window: "10s" }
        );
        if (errorMessage) throw new Error(errorMessage);
        return [{ id: "1" }];
      },
    },
  },
});

Option 3: Using the base rate limiter function with deferred commit new access

import { getDeferredGraphQLRateLimiter } from "graphql-rate-limit";

const rateLimiter = getDeferredGraphQLRateLimiter({
  identifyContext: (ctx) => ctx.id,
});
const schema = makeExecutableSchema({
  resolvers: {
    Mutation: {
      test: async (parent, args, context, info) => {
        const { error, saveRate } = await rateLimiter(
          { parent, args, context, info },
          { max: 1, window: "1s" }
        );
        if (error) throw new Error(error);
        // you manually commit the recent access
        await saveRate();
        return "Result";
      },
    },
  },
  typeDefs: `
    type Mutation {
      test: String!
    }
    type Query {
      test: String!
    }
  `,
});

Configuration

You'll notice that each usage example has two steps, step 1 we get an instace of a rate limiter and step 2 we apply the rate limit to one or more fields. When creating the initial instance we pass 'Instance Config' (e.g. identifyContext or a store instance), this instance will likely be the only instance you'd create for your entire GraphQL backend and can be applied to multiple fields.

Once you have your rate limiting instance you'll apply it to all the fields that require rate limiting, at this point you'll pass field level rate limiting config (e.g. window and max).

And so... we have the same 'Instance Config' and 'Field Config' options which ever way you use this library.

Instance Config

identifyContext

A required key and used to identify the user/client. The most likely cases are either using the context's request.ip, or the user ID on the context. A function that accepts the context and returns a string that is used to identify the user.

identifyContext: (ctx) => ctx.user.id;

store

An optional key as it defaults to an InMemoryStore. See the implementation of InMemoryStore if you'd like to implement your own with your own database.

store: new MyCustomStore();

formatError

Generate a custom error message. Note that the message passed in to the field config will be used if its set.

formatError: ({ fieldName }) =>
  `Woah there, you are doing way too much ${fieldName}`;

enableBatchRequestCache

This enables a per-request synchronous cache to properly rate limit batch queries. Defaults to true.

enableBatchRequestCache: false | true;

Field Config

window

Specify a time interval window that the max number of requests can access the field. We use Zeit's ms to parse the window arg, docs here.

max

Define the max number of calls to the given field per window.

identityArgs

If you wanted to limit the requests to a field per id, per user, use identityArgs to define how the request should be identified. For example you'd provide just ["id"] if you wanted to rate limit the access to a field by id. We use Lodash's get to access nested identity args, docs here.

message

A custom message per field. Note you can also use formatError to customise the default error message if you don't want to define a single message per rate limited field.

arrayLengthField

Limit calls to the field, using the length of the array as the number of calls to the field.

Redis Store Usage

It is recommended to use a persistent store rather than the default InMemoryStore. GraphQLRateLimit currently supports Redis as an alternative. You'll need to install Redis in your project first.