initial commit.
This commit is contained in:
48
app/i18n/api.ts
Normal file
48
app/i18n/api.ts
Normal file
@ -0,0 +1,48 @@
|
||||
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);
|
||||
}
|
||||
}
|
9
app/i18n/lang.ts
Normal file
9
app/i18n/lang.ts
Normal file
@ -0,0 +1,9 @@
|
||||
export const LANGUAGES = [
|
||||
"en",
|
||||
"es",
|
||||
"fr",
|
||||
"uk",
|
||||
"rs",
|
||||
]
|
||||
|
||||
export type language_t = typeof LANGUAGES[number];
|
Reference in New Issue
Block a user