@crowdin/app-project-module
Version:
Module that generates for you all common endpoints for serving standalone Crowdin App
62 lines (61 loc) • 3.18 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.reportInsight = reportInsight;
const axios_1 = __importDefault(require("axios"));
const storage_1 = require("../../storage");
const connection_1 = require("../../util/connection");
const logger_1 = require("../../util/logger");
function buildBody(args) {
var _a, _b;
return Object.assign(Object.assign(Object.assign({ outcome: args.outcome }, (args.checkedAt !== undefined && { checkedAt: args.checkedAt })), { metrics: (_a = args.metrics) !== null && _a !== void 0 ? _a : [], recommendations: (_b = args.recommendations) !== null && _b !== void 0 ? _b : [] }), (args.payload !== undefined && { payload: args.payload }));
}
function put(url_1, body_1, token_1) {
return __awaiter(this, arguments, void 0, function* (url, body, token, timeoutMs = 300000) {
yield axios_1.default.put(url, body, {
headers: { Authorization: `Bearer ${token}` },
timeout: timeoutMs,
});
});
}
function isUnauthorized(e) {
const response = e === null || e === void 0 ? void 0 : e.response;
return !!response && response.status === 401;
}
function reportInsight(config, args) {
return __awaiter(this, void 0, void 0, function* () {
const credentials = yield (0, storage_1.getStorage)().getCrowdinCredentials(args.crowdinId);
if (!credentials) {
throw new Error(`reportInsight: no credentials for crowdinId=${args.crowdinId}`);
}
const body = buildBody(args);
const initial = yield (0, connection_1.prepareCrowdinClient)({ config, credentials, autoRenew: true });
let token = initial.token;
const url = `${initial.client.url}/projects/${args.projectId}` +
`/applications/${config.identifier}` +
`/modules/${args.moduleKey}/advisors/insights`;
try {
yield put(url, body, token, args.timeoutMs);
}
catch (e) {
if (isUnauthorized(e)) {
({ token } = yield (0, connection_1.prepareCrowdinClient)({ config, credentials, autoRenew: true }));
yield put(url, body, token, args.timeoutMs);
return;
}
(0, logger_1.log)(`reportInsight PUT failed: ${(0, logger_1.getErrorMessage)(e)}`);
throw e;
}
});
}