ai-fetcher
Version:
A Node.js package that provides integration with popular language models. It is designed to facilitate easy and efficient ai-fetching tasks for your application.
77 lines (76 loc) • 3.23 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DeepL = void 0;
const axios_1 = __importDefault(require("axios"));
// The DeepL Agent class
class DeepL {
/**
* Construcs a new instance of DeepL class
* @param deepLKey: string - The user's DeepL authentication key
* @param isPro (optional) - boolean. Specifies if the user is using the pro version api
*/
constructor(deepLKey, isPro = false) {
this.apiKey = deepLKey;
this.isPro = isPro;
this.endpoints = {
free: "https://api-free.deepl.com/v2/translate",
pro: "https://api.deepl.com/v2/translate",
};
this.url = this.isPro
? this.endpoints["pro"]
: this.endpoints["free"];
this.headers = {
Authorization: `DeepL-Auth-Key ${this.apiKey}`,
"Content-Type": "application/json",
};
}
/**
* Translate the given text fron one language to another
* The input is an JavaScript Object
* @param from (optional): string - Should be one of the supported language.
* @param to: string - Should be one of the supported language.
* @param text: string[] | string - The source text(s) to be translated.
*
* @returns A Promise that resolves to a DeepLResult containing the translation
* @throws An error if the API request fails
*/
translate(_a) {
return __awaiter(this, arguments, void 0, function* ({ from, to, text, }) {
// DeepL requires the input text to be an array of strings
const inputText = typeof text === "string" ? [text] : text;
const data = {
text: inputText,
target_lang: to.toUpperCase(),
};
// source_lang is an optional attribute for the DeepL request
if (from) {
data.source_lang = from.toUpperCase();
}
try {
const response = yield axios_1.default.post(this.url, data, {
headers: this.headers,
});
return response.data;
}
catch (error) {
if (error instanceof Error)
throw new Error(error.message);
else
throw new Error(String(error));
}
});
}
}
exports.DeepL = DeepL;