2025-01-22 18:57:32 -08:00

48 lines
1.5 KiB
TypeScript

import { language_t } from "./lang";
import { Cache } from "react-native-cache";
import AsyncStorage from '@react-native-async-storage/async-storage';
import { LIBRETRANSLATE_BASE_URL } from "@/constants/api";
const cache = new Cache({
namespace: "translation_terrace",
policy: {
maxEntries: 50000, // if unspecified, it can have unlimited entries
stdTTL: 0 // the standard ttl as number in seconds, default: 0 (unlimited)
},
backend: AsyncStorage
});
export class Translator {
constructor(public source : language_t, public target : language_t) {
}
async translate(text : string) {
const url = LIBRETRANSLATE_BASE_URL + `/translate`;
const res = await fetch(url, {
method: "POST",
body: JSON.stringify({
q: text,
source: this.source,
target: this.target,
format: "text",
alternatives: 3,
api_key: ""
}),
headers: { "Content-Type": "application/json" }
});
const data = await res.json();
return data.translatedText
}
}
export class CachedTranslator extends Translator {
async translate (text : string) {
const key1 = `${this.source}::${this.target}::${text}`
const tr1 = await cache.get(key1);
if (tr1) return tr1;
const tr2 = await super.translate(text);
const key2 = `${this.source}::${this.target}::${text}`
await cache.set(key2, tr2);
}
}