diff --git a/pages/api/generate.ts b/pages/api/generate.ts index 022b9d2..0d9c2f6 100644 --- a/pages/api/generate.ts +++ b/pages/api/generate.ts @@ -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!
`, + 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!
`, + ], + }, + }; + } 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' }); } } diff --git a/supabase.md b/supabase.md new file mode 100644 index 0000000..ca7cb38 --- /dev/null +++ b/supabase.md @@ -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**.