-
-
Notifications
You must be signed in to change notification settings - Fork 162
Prisma
Roman edited this page Feb 15, 2024
·
7 revisions
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.
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?
}
-
Generate Prisma client with
prisma generate --schema=./schema.prisma
-
Create tables or collections with
prisma db push --schema=./schema.prisma
Get started
Middlewares and plugins
Migration from other packages
Limiters:
- Redis
- Memory
- DynamoDB
- Prisma
- MongoDB (with sharding support)
- PostgreSQL
- MySQL
- BurstyRateLimiter
- Cluster
- PM2 Cluster
- Memcached
- RateLimiterUnion
- RateLimiterQueue
Wrappers:
- RLWrapperBlackAndWhite Black and White lists
Knowledge base:
- Block Strategy in memory
- Insurance Strategy
- Comparative benchmarks
- Smooth out traffic peaks
-
Usage example
- Minimal protection against password brute-force
- Login endpoint protection
- Websocket connection prevent flooding
- Dynamic block duration
- Different limits for authorized users
- Different limits for different parts of application
- Block Strategy in memory
- Insurance Strategy
- Third-party API, crawler, bot rate limiting