Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] feat: upstash redis rate limit #2

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion supabase/functions/import_map.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"sift": "https://deno.land/x/[email protected]/mod.ts",
"@supabase/supabase-js": "https://esm.sh/@supabase/[email protected]",
"postgres": "https://deno.land/x/[email protected]/mod.ts",
"Redis": "https://deno.land/x/[email protected]/mod.ts"
"@upstash/redis": "https://deno.land/x/[email protected]/mod.ts",
"@upstash/ratelimit": "https://esm.sh/@upstash/[email protected]"
}
}
2 changes: 1 addition & 1 deletion supabase/functions/upstash-redis-counter/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { serve } from "std/server";
import { Redis } from "Redis";
import { Redis } from "@upstash/redis";
console.log(`Function "upstash-redis-counter" up and running!`);
serve(async (_req) => {
try {
Expand Down
34 changes: 34 additions & 0 deletions supabase/functions/upstash-redis-ratelimiter/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { serve } from "std/server";
import { Redis } from "@upstash/redis";
import { Ratelimit } from "https://esm.sh/@upstash/[email protected]";

console.log(`Function "upstash-redis-ratelimiter" up and running!`);
serve(async (_req) => {
try {
const redis = new Redis({
url: Deno.env.get("UPSTASH_REDIS_REST_URL")!,
token: Deno.env.get("UPSTASH_REDIS_REST_TOKEN")!,
});

// Create a new ratelimiter, that allows 10 requests per 10 seconds
const ratelimit = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(2, "10 s"),
analytics: true,
});

// Use a constant string to limit all requests with a single ratelimit
// Or use a userID, apiKey or ip address for individual limits.
const identifier = "api";
const { success } = await ratelimit.limit(identifier);

if (!success) {
throw new Error("limit exceeded");
}
return new Response(JSON.stringify({ success }), { status: 200 });
} catch (error) {
return new Response(JSON.stringify({ error: error.message }), {
status: 200,
});
}
});