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

feat: Implement rate limiting using Supabase SQL for 5 API requests per day for each user #53

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
47 changes: 33 additions & 14 deletions pages/api/generate.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,62 @@
const axios = require("axios");
import { createClient } from "@supabase/supabase-js";
const axios = require('axios');
import { createClient } from '@supabase/supabase-js';

export default async function handler(req: any, res: any) {
if (req.method === "POST") {
if (req.method === 'POST') {
// Process a POST request
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL as string,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY as string
);

const {
data: { user },
} = await supabase.auth.getUser(req.headers.token as string);
if (!user) {
return res.status(401).json({ error: "Not authorized" });
return res.status(401).json({ error: 'Not authorized' });
}
let axiosConfig = {
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*",
"X-API-KEY": process.env.SANATAN_AI_API_KEY,
'Content-Type': 'application/json;charset=UTF-8',
'Access-Control-Allow-Origin': '*',
'X-API-KEY': process.env.SANATAN_AI_API_KEY,
},
};
let question = req.body.question;
let chat_history = req.body.chat_history;

let payload = {
question: question,
question: question,
chat_history: chat_history,
};

let generations = await axios.post(
`${process.env.SANATAN_AI_API_URL}content/bhagavad_gita`,
payload,
axiosConfig
);
const { data: apiCount, error } = await supabase.rpc('incrementcount', {
id: user.id,
});

let generations;
if (apiCount === 0) {
generations = {
data: {
answer: `We humbly ask for your patience, as you have made the maximum number of requests for today. Please visit us again tomorrow for more guidance. Radhey Radhey!<br>`,
chat_history: [
...chat_history,
`Human: ${question} \n` +
`AI: We humbly ask for your patience, as you have made the maximum number of requests for today. Please visit us again tomorrow for more guidance. Radhey Radhey!<br>`,
],
},
};
} else {
generations = await axios.post(
`${process.env.SANATAN_AI_API_URL}content/bhagavad_gita`,
payload,
axiosConfig
);
}

let data = generations.data;
return res.json(data);
} else {
return res.status(200).json({ message: "Radhey Radhey Dear Devotee" });
return res.status(200).json({ message: 'Radhey Radhey Dear Devotee' });
}
}
62 changes: 62 additions & 0 deletions supabase.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Setting up Supabase for Sql table for the rate limiter

This guide will walk you through the process of setting up Supabase for use with Next.js, to create the sql table and query that is required to limit users 5 api requests per day.

## Creating table requests

1. Open the SQL editor on the Supabase dashboard.
2. Create a new query:

```sql
CREATE TABLE requests (
u_id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
created_at timestamptz DEFAULT (now() AT TIME ZONE 'utc'::text),
user_id uuid,
updated_at timestamptz DEFAULT (now() AT TIME ZONE 'utc'::text),
count int2 DEFAULT 0
);
```

3. Run the query to create the table **requests** with the specified columns.
4. Go to Table Editor section on supabase, you will find that the table is created.

### Creating the IncrementCount Function

1. Open the SQL editor on the Supabase dashboard.
2. In the SQL editor, run the following query:

```sql
CREATE OR REPLACE FUNCTION incrementCount(id uuid)
RETURNS int AS $$
DECLARE
cnt integer;
BEGIN
IF EXISTS (SELECT 1 FROM requests WHERE user_id = id) THEN
SELECT count INTO cnt FROM requests WHERE user_id = id;
IF DATE_TRUNC('day', (SELECT created_at AT TIME ZONE 'UTC' FROM requests WHERE user_id = id)) < DATE_TRUNC('day', CURRENT_TIMESTAMP AT TIME ZONE 'UTC') THEN
UPDATE requests
SET count = 1,
created_at = CURRENT_TIMESTAMP,
updated_at = CURRENT_TIMESTAMP
WHERE user_id = id;
RETURN 1;
ELSEIF cnt = 5 THEN
RETURN 0;
ELSE
UPDATE requests
SET count = count + 1,
updated_at = CURRENT_TIMESTAMP
WHERE user_id = id;
RETURN cnt + 1;
END IF;
ELSE
INSERT INTO requests (user_id, count, created_at, updated_at)
VALUES (id, 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);
RETURN 1;
END IF;
END;
$$ LANGUAGE plpgsql VOLATILE;

```

3. Run the query to create the function **incrementCount**.