UNPKG

@dvhb/react-intl-messages

Version:

Library for parsing source files and extract react-intl messages

75 lines (74 loc) 2.88 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../utils"); const BASE_URL = 'https://api.locize.io'; class Locize { constructor(defaultLocale, projectId, apiKey, version, namespace) { this.defaultLocale = defaultLocale; this.projectId = projectId; this.apiKey = apiKey; this.version = version; this.namespace = namespace; this.locizeKeys = {}; this.newMessages = []; } static getHeaders(apiKey) { return Object.assign({ 'content-type': 'application/json' }, (apiKey ? { Authorization: `Bearer ${apiKey}` } : {})); } formatMessages(messages, isDefaultLocale) { return messages.reduce((acc, { id, message, defaultMessage, description }) => { acc[id] = { value: isDefaultLocale ? message || defaultMessage : message || '', context: { text: description || '' }, }; return acc; }, {}); } async getKeys(locales) { utils_1.showInfo('Start fetching messages from Locize'); const headers = Locize.getHeaders(); return utils_1.asyncForEach(locales, async (locale) => { try { this.locizeKeys[locale] = await utils_1.request({ headers, url: `${BASE_URL}/${this.projectId}/${this.version}/${locale}/${this.namespace}`, method: 'GET', }); utils_1.showInfo('Finish fetching messages from Locize'); } catch (e) { utils_1.showError(`Error while fetching strings from locize\n${e}`); } }); } getMessage(locale, id) { const key = Object.keys(this.locizeKeys[locale]).find(key => key === id); if (key) { return this.locizeKeys[locale][key]; } if (locale === this.defaultLocale) { this.newMessages.push(id); } return ''; } async uploadMessages(messages, locale = this.defaultLocale) { const isDefaultLocale = locale === this.defaultLocale; const uploadMethod = isDefaultLocale ? 'missing' : 'update'; try { const response = await utils_1.request({ headers: Locize.getHeaders(this.apiKey), body: this.formatMessages(messages, isDefaultLocale), url: `${BASE_URL}/${uploadMethod}/${this.projectId}/${this.version}/${locale}/${this.namespace}`, method: 'POST', }); utils_1.showInfo(`Response from locize: ${JSON.stringify(response, null, 2)}`); } catch (e) { utils_1.showError(`Error while uploading strings to locize\n${e}`); } } getNewMessages() { return this.newMessages; } } exports.Locize = Locize;