UNPKG

@atrysglobal/babel-ripper

Version:

Interface and strict typing toolkit for accessing the BABEL unified translation service.

226 lines (225 loc) 8.77 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const babel_ripper_1 = require("../babel-ripper"); const enums_1 = require("./enums"); const handler_lib_1 = require("./libs/handler.lib"); const http_lib_1 = require("./libs/http.lib"); const templates_lib_1 = require("./libs/templates.lib"); /** * Manages the organized retrieval of translations and pre-built * of error messages from atrys babel service. * * Babel Service is organized in two main sections: * * - Translations: Used to retrieve translations * for a given target. * - Interpreter: Used to retrieve pre-built error * messages for a given target. * * Also provides a method to retrieve translations * from a given structured object via Ripper tool. * */ class BabelProxyService { constructor(options) { // Api Key must be specified in any case and must // not be an empty string. if (!options || !options.apiKey || !options.apiKey.length) { throw new Error('Babel Implementation Exception: Must provide a valid API key. Contact support center for more information.'); } // Api Address must be specified in any case and must // not be an empty string. const serviceApiAddress = options.apiAddress || process.env.BABEL_SERVICE; if (!serviceApiAddress || !serviceApiAddress.length) { throw new Error('Babel Implementation Exception: Must provide a valid API address. Contact support center for more information.'); } // Obtain shared axios instance. this.httpInstance = http_lib_1.BabelProxyHttp.getAxiosInstance({ apiKey: options.apiKey, baseURL: serviceApiAddress, timeout: options.clientTimeout, }); // Obtain shared babel api address. this.serviceUrl = serviceApiAddress; // Configure shared default locale. this.defaultLocale = options && options.defaultLocale?.length ? options.defaultLocale : enums_1.LOCALES.es_ES; // Configure default response mechanism // (by default service always responds with status 200). this.recoveryMessagingTemplate = options && options?.defaultOkResponse === true ? templates_lib_1.okMessagingTemplate : templates_lib_1.disasterMessagingTemplate; this.recoveryInterpreterTemplate = []; } resolveCorePayload(mod, payload) { const base = { module: mod, }; if (mod === enums_1.BABEL_FEATURES.MESSAGING) { Object.assign(base, { message: payload }); } else { Object.assign(base, { translations: payload }); } return base; } /** * Core handler for Messaging features. * * @param {Method} method - HTTP verb to use. * @param {unknown} payload - Payload to send. * @param {BabelRequestOptions} options - Options to use. * * @returns {Promise<BabelMessagingResult>} - Promise with the result. */ async coreMessaging(method, payload, options) { try { const transactionConfig = { headers: { [enums_1.ALLOWED_HEADERS.LOCALE]: options?.locale || this.defaultLocale, }, }; const response = await this.httpInstance.request({ baseURL: `${this.serviceUrl}`, method: method, data: this.resolveCorePayload(enums_1.BABEL_FEATURES.MESSAGING, payload), headers: transactionConfig.headers, }); if (response.data) { const { id, message, httpCode, internalCode } = response.data; return { id, message, httpCode, internalCode, }; } return this.recoveryMessagingTemplate; } catch (error) { handler_lib_1.BabelHandler.fromAxios(error); throw Error(`INTERNAL Exception while obtaining [BABEL] message(s): ${error}`); } } /** * Core handler for Interpreter features. * * @param {Method} method - HTTP verb to use. * @param {unknown} payload - Payload to send. * @param {BabelRequestOptions} options - Options to use. * * @returns {Promise<BabelMessagingResult[]>} - Promise with the result. */ async coreInterpreter(method, payload, options) { try { const transactionConfig = { headers: { [enums_1.ALLOWED_HEADERS.LOCALE]: options?.locale || this.defaultLocale, }, }; const response = await this.httpInstance.request({ baseURL: `${this.serviceUrl}`, method: method, data: this.resolveCorePayload(enums_1.BABEL_FEATURES.INTERPRETER, payload), headers: transactionConfig.headers, }); if (response.data) { return response.data; } return this.recoveryInterpreterTemplate; } catch (error) { handler_lib_1.BabelHandler.fromAxios(error); throw Error(`INTERNAL Exception while obtaining [BABEL] translation(s): ${error}`); } } /** * Manages the translation of multiple messages * through a reference list (i18n). * * Includes support for interpolation of parameters. * * @param {BabelTargetInterface[]} targetList - Translations reference list. * @param {BabelRequestOptions} options - On-the-fly configuration options. * @returns {BabelMessagingResult[]} - List of translated messages. */ loadTranslations(targetList, options) { return this.coreInterpreter(enums_1.HTTP_VERB.POST, targetList, options); } /** * Message translation process tool through * reference dictionary (i18n). * * This tool will respond with a BabelMessagingResult * array. This mean that the translation result extracted * and/or processing have to be defined by the client. * * @param {ITranslationPayload} dictionaryKeyPair - Reference dictionary. * @param {BabelRequestOptions} options - On-the-fly configuration options. * @returns {BabelMessagingResult[]} - List of translated messages. */ loadTranslationsFromObject(dictionaryKeyPair, options) { const converted = Object.values(dictionaryKeyPair).map((target) => { if (typeof target === 'string') { return { target }; } else if (target.target) { const obs = { target: target.target }; if (target.params) { Object.assign(obs, { params: target.params }); } return obs; } else { throw new Error('Fatal error'); } }); return this.loadTranslations(converted, options); } /** * Message translation process tool through * reference dictionary (i18n). * * This tool will respond with a BabelRipper * object for an organized handling of translations. * * @example * * const dictionary = { * hello: 'messages.hello', * bye: 'messages.bye' * } * * const babel = new BabelProxyService(...); * const result = await babel.loadGuttedTranslations(dictionary); * * result.get(dictionary.hello); // Hola! * result.get(dictionary.bye); // Adiós! * * * @param {ITranslationPayload} dictionaryKeyPair - Reference dictionary. * @param {BabelRequestOptions} options - On-the-fly configuration options. * @returns {BabelRipper} - Organized translation object. */ async loadGuttedTranslations(dictionaryKeyPair, options) { const translations = await this.loadTranslationsFromObject(dictionaryKeyPair, options); return new babel_ripper_1.BabelRipper(translations); } /** * Get a pre-defined message (success or error) * translated through the babel service. * * Includes support for interpolation of parameters. * * @param {BabelTargetInterface} target - Object with message reference to be translated. * @param {BabelRequestOptions} options - On-the-fly configuration options. * @returns {BabelMessagingResult} - Translated message (or List of translated messages). */ async loadMessage(target, options) { return this.coreMessaging(enums_1.HTTP_VERB.POST, target, options); } } exports.default = BabelProxyService;