diff --git a/supabase/functions/import_map.json b/supabase/functions/import_map.json index a9b32fa..812f016 100644 --- a/supabase/functions/import_map.json +++ b/supabase/functions/import_map.json @@ -9,6 +9,7 @@ "sift": "https://deno.land/x/sift@0.6.0/mod.ts", "@supabase/supabase-js": "https://esm.sh/@supabase/supabase-js@2.4.0", "postgres": "https://deno.land/x/postgres@v0.14.2/mod.ts", - "Redis": "https://deno.land/x/upstash_redis@v1.19.3/mod.ts" + "@upstash/redis": "https://deno.land/x/upstash_redis@v1.19.3/mod.ts", + "@upstash/ratelimit": "https://esm.sh/@upstash/ratelimit@0.3.7" } } diff --git a/supabase/functions/upstash-redis-counter/index.ts b/supabase/functions/upstash-redis-counter/index.ts index c9eb2ac..1f289a0 100644 --- a/supabase/functions/upstash-redis-counter/index.ts +++ b/supabase/functions/upstash-redis-counter/index.ts @@ -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 { diff --git a/supabase/functions/upstash-redis-ratelimiter/index.ts b/supabase/functions/upstash-redis-ratelimiter/index.ts new file mode 100644 index 0000000..60a491b --- /dev/null +++ b/supabase/functions/upstash-redis-ratelimiter/index.ts @@ -0,0 +1,34 @@ +import { serve } from "std/server"; +import { Redis } from "@upstash/redis"; +import { Ratelimit } from "https://esm.sh/@upstash/ratelimit@0.3.3"; + +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, + }); + } +});