Skip to content
Roman edited this page Feb 15, 2024 · 7 revisions

RateLimiterPrisma

Tested with Prisma version ^5.8.0.

Note, model table should be already created before creating rateLimiter.

const http = require('http');
const { RateLimiterPrisma } = require('rate-limiter-flexible');
const { PrismaClient } = require('@prisma/client');

const prisma = new PrismaClient();

const rateLimiter = new RateLimiterPrisma({
  storeClient: prisma,
  points: 3, // Number of points
  duration: 5, // Per second(s)
})

async function rateLimit(userId) {
  try {
    const rlRes = await rateLimiter.consume(userId, 1) // consume 1 point
    console.log(rlRes)
        // {
        // remainingPoints: 2,
        // msBeforeNext: 4976,
        // consumedPoints: 1,
        // isFirstInDuration: true
        // }
  } catch (rejRes) {
    if (rejRes instanceof Error) {
      // Some error
      // It never happens if `insuranceLimiter` is configured
    } else {
      // If there is no error, rateLimiterPrisma promise is rejected with number of ms before next request allowed
      // For example, in express.js you could set headers and send 429
      // const secs = Math.round(rejRes.msBeforeNext / 1000) || 1;
      // res.set('Retry-After', String(secs));
      // res.status(429).send('Too Many Requests');
    }

    throw rejRes
  }
}

The full documentation is on Wiki.

Schema example

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = "postgres://root:secret@localhost:5432"
}

model RateLimiterFlexible {
  key     String   @id
  points  Int
  expire  DateTime?
}

Commands to run before the first launch

  1. Generate Prisma client with

    prisma generate --schema=./schema.prisma

  2. Create tables or collections with

    prisma db push --schema=./schema.prisma

Clone this wiki locally