(req: NextRequest)
| 91 | const headers = { "Content-Type": "application/json" }; |
| 92 | |
| 93 | export default async function handler(req: NextRequest) { |
| 94 | try { |
| 95 | console.log("/api/v1/answers called!"); |
| 96 | // Handle CORS preflight request |
| 97 | if (req.method === "OPTIONS") { |
| 98 | return new Response(undefined, { status: 200 }); |
| 99 | } |
| 100 | // Handle non-POST requests |
| 101 | if (req.method !== "POST") { |
| 102 | return new Response( |
| 103 | JSON.stringify({ |
| 104 | error: "Only POST requests allowed", |
| 105 | }), |
| 106 | { status: 405, headers }, |
| 107 | ); |
| 108 | } |
| 109 | |
| 110 | // Authenticate that the user is allowed to use this API |
| 111 | const orgApiKey = req.headers |
| 112 | .get("Authorization") |
| 113 | ?.replace("Bearer ", "") |
| 114 | .replace("bearer ", ""); |
| 115 | |
| 116 | if (!orgApiKey) { |
| 117 | return new Response(JSON.stringify({ error: "Authentication failed" }), { |
| 118 | status: 401, |
| 119 | headers, |
| 120 | }); |
| 121 | } |
| 122 | |
| 123 | // Check that the user hasn't surpassed the production rate limit (protects DB query below) |
| 124 | if (ratelimitProduction) { |
| 125 | // If over limit, success is false |
| 126 | const { success } = await ratelimitProduction.limit(orgApiKey); |
| 127 | if (!success) { |
| 128 | return new Response( |
| 129 | JSON.stringify({ error: "Rate limit hit (30 requests/10s)" }), |
| 130 | { |
| 131 | status: 429, |
| 132 | headers, |
| 133 | }, |
| 134 | ); |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | let org: OrgJoinIsPaidFinetunedModels | null = null; |
| 139 | if (orgApiKey) { |
| 140 | const authRes = await serviceLevelSupabase |
| 141 | .from("organizations") |
| 142 | .select( |
| 143 | "id,name,api_key,description,model,sanitize_urls_first,language,chat_to_docs_enabled,chatbot_instructions,bertie_enabled,fun_loading_messages,bertie_disable_direct,enable_data_analysis,yond_cassius,fallback_to_bertie, is_paid(is_premium), finetuned_models(openai_name)", |
| 144 | ) |
| 145 | .eq("api_key", orgApiKey); |
| 146 | if (authRes.error) throw new Error(authRes.error.message); |
| 147 | org = authRes.data?.[0] ?? null; |
| 148 | } |
| 149 | if (!org) { |
| 150 | return new Response(JSON.stringify({ error: "Authentication failed" }), { |
nothing calls this directly
no test coverage detected