UNPKG

attranslate

Version:

Text Translator for Websites and Apps

53 lines (52 loc) 2.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AzureTranslator = void 0; const tslib_1 = require("tslib"); const node_fetch_1 = (0, tslib_1.__importDefault)(require("node-fetch")); const lodash_1 = require("lodash"); const util_1 = require("../util/util"); const TRANSLATE_ENDPOINT = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0"; class AzureTranslator { async translateBatch(batch, args, config) { var _a; const [apiKey, region] = (_a = config === null || config === void 0 ? void 0 : config.split(',')) !== null && _a !== void 0 ? _a : []; if (!apiKey) { throw new Error('Missing API Key'); } const headers = { "Ocp-Apim-Subscription-Key": apiKey, "Content-Type": "application/json; charset=UTF-8", }; if (region) { headers["Ocp-Apim-Subscription-Region"] = region; } const azureBody = batch.map((tString) => { return { Text: tString.value, }; }); const response = await (0, node_fetch_1.default)(`${TRANSLATE_ENDPOINT}&from=${args.srcLng}&to=${args.targetLng}&textType=html`, { method: "POST", headers, body: JSON.stringify(azureBody), }); if (!response.ok) { throw new Error("Azure Translation failed: " + (await response.text())); } const data = (await response.json()); return data.map((res, i) => ({ key: batch[i].key, translated: res.translations[0].text, })); } async translateStrings(args) { const config = args.serviceConfig; if (!config) { (0, util_1.logFatal)("Set '--serviceConfig' to an Azure API key"); } const batches = (0, lodash_1.chunk)(args.strings, 50); const results = await Promise.all(batches.map((batch) => this.translateBatch(batch, args, config))); return (0, lodash_1.flatten)(results); } } exports.AzureTranslator = AzureTranslator;