api: load balance of the API keys for deepl translate, closes #429 (#431)

This commit is contained in:
Huang Xin
2025-02-22 09:09:25 +01:00
committed by GitHub
parent 66784736ee
commit e96782baab
3 changed files with 21 additions and 4 deletions
+2 -2
View File
@@ -4,8 +4,8 @@ NEXT_PUBLIC_POSTHOG_HOST=YOUR_POSTHOG_HOST
NEXT_PUBLIC_SUPABASE_URL=YOUR_SUPABASE_URL
NEXT_PUBLIC_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY
DEEPL_PRO_API_KEY=YOUR_DEEPL_PRO_API_KEY
DEEPL_FREE_API_KEY=YOUR_DEEPL_FREE_API_KEY
DEEPL_PRO_API_KEYS=YOUR_DEEPL_PRO_API_KEYS
DEEPL_FREE_API_KEYS=YOUR_DEEPL_FREE_API_KEYS
R2_TOKEN_VALUE=YOUR_R2_TOKEN_VALUE
R2_ACCESS_KEY_ID=YOUR_R2_ACCESS_KEY_ID
@@ -1,6 +1,7 @@
import { NextApiRequest, NextApiResponse } from 'next';
import { corsAllMethods, runMiddleware } from '@/utils/cors';
import { supabase } from '@/utils/supabase';
import { getUserPlan } from '@/utils/access';
const DEEPL_FREE_API = 'https://api-free.deepl.com/v2/translate';
const DEEPL_PRO_API = 'https://api.deepl.com/v2/translate';
@@ -18,11 +19,22 @@ const getUserAndToken = async (authHeader: string | undefined) => {
return { user, token };
};
const getDeepLAPIKey = (keys: string | undefined) => {
const keyArray = keys?.split(',') ?? [];
return keyArray[Math.floor(Math.random() * keyArray.length)];
};
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const { user, token } = await getUserAndToken(req.headers['authorization']);
const deeplApiUrl = user && token ? DEEPL_PRO_API : DEEPL_FREE_API;
let deeplApiUrl = DEEPL_FREE_API;
if (user && token) {
const userPlan = await getUserPlan(token);
if (userPlan !== 'free') deeplApiUrl = DEEPL_PRO_API;
}
const deeplAuthKey =
user && token ? process.env['DEEPL_PRO_API_KEY'] : process.env['DEEPL_FREE_API_KEY'];
deeplApiUrl === DEEPL_PRO_API
? getDeepLAPIKey(process.env['DEEPL_PRO_API_KEYS'])
: getDeepLAPIKey(process.env['DEEPL_FREE_API_KEYS']);
await runMiddleware(req, res, corsAllMethods);
+5
View File
@@ -10,6 +10,11 @@ interface Token {
[key: string]: string | number;
}
export const getUserPlan = async (token: string): Promise<UserPlan> => {
const data = jwtDecode<Token>(token) || {};
return data['plan'] || 'free';
};
export const getStoragePlanData = (token: string) => {
const data = jwtDecode<Token>(token) || {};
const plan = data['plan'] || 'free';