@altravia/openapi
Version:
Official OpenApi NodeJS Client
218 lines (217 loc) • 11.1 kB
JavaScript
"use strict";
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 __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var axios_1 = __importDefault(require("axios"));
var Comuni_1 = require("./Services/Comuni");
var Geocoding_1 = require("./Services/Geocoding");
var Imprese_1 = require("./Services/Imprese");
var utils_1 = require("./utils");
var Pa_1 = require("./Services/Pa");
var FirmaDigitale_1 = require("./Services/FirmaDigitale");
var MarcheTemporali_1 = require("./Services/MarcheTemporali");
var PecMassiva_1 = require("./Services/PecMassiva");
var Valutometro_1 = require("./Services/Valutometro");
var SplitPayment_1 = require("./Services/SplitPayment");
var EuropeanVat_1 = require("./Services/EuropeanVat");
var Visengine_1 = require("./Services/Visengine");
var Postontarget_1 = require("./Services/Postontarget");
var Domains_1 = require("./Services/Domains");
var Sms_1 = require("./Services/Sms");
var UfficioPostale_1 = require("./Services/UfficioPostale");
var OpenApi = /** @class */ (function () {
function OpenApi(environment, username, apiKey) {
this.scopes = [];
this.username = username;
this.apiKey = apiKey;
this.environment = environment;
}
/**
* Crea il client di connessione con OpenApi
* Se l'autoRenew è attivo, controllerá lo stato del token
* prima di istanziare il client, ed in caso lo rinnoverà
*/
OpenApi.prototype.createClient = function (token, autoRenew) {
if (autoRenew === void 0) { autoRenew = true; }
return __awaiter(this, void 0, void 0, function () {
var tokenData, scopes, err_1;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this.token = token;
_a.label = 1;
case 1:
_a.trys.push([1, 7, , 8]);
return [4 /*yield*/, axios_1.default.get(this.getOauthUrl() + '/token/' + token, {
auth: { username: this.username, password: this.apiKey }
})];
case 2:
tokenData = _a.sent();
if (!(tokenData.status === 200)) return [3 /*break*/, 5];
scopes = tokenData.data.data[0].scopes;
scopes.forEach(function (scope) {
var url = OpenApi.splitScope(scope);
_this.scopes.push({ mode: scope.split(':', 1), domain: url[0], method: url[1] });
});
if (!(autoRenew && tokenData.data.data[0].expire < ((Math.floor(Date.now() / 1000) + (86400 * 15))))) return [3 /*break*/, 4];
return [4 /*yield*/, this.renewToken(this.token)];
case 3:
_a.sent();
_a.label = 4;
case 4: return [3 /*break*/, 6];
case 5:
if (tokenData.status === 204) {
throw 'The provided token does not exists or it was deleted';
}
_a.label = 6;
case 6: return [3 /*break*/, 8];
case 7:
err_1 = _a.sent();
throw err_1;
case 8:
this.client = axios_1.default.create({
headers: { 'Authorization': 'Bearer ' + this.token }
});
[Comuni_1.Comuni, Sms_1.Sms, Imprese_1.Imprese, Geocoding_1.Geocoding, Pa_1.Pa, FirmaDigitale_1.FirmaDigitale, MarcheTemporali_1.MarcheTemporali, PecMassiva_1.PecMassiva,
Valutometro_1.Valutometro, SplitPayment_1.Splitpayment, EuropeanVat_1.EuropeanVat, Visengine_1.Visengine, Postontarget_1.Postontarget, Domains_1.Domains, UfficioPostale_1.UfficioPostale
].forEach(function (service) {
//@ts-ignore
var s = new service(_this.client, _this.environment);
if (utils_1.isServiceInScopes(_this.scopes, s.baseUrl)) {
//@ts-ignore
_this[s.service] = s;
}
});
return [2 /*return*/, this];
}
});
});
};
OpenApi.prototype.renewToken = function (token) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, axios_1.default.patch(this.getOauthUrl() + '/token/' + token, { expire: 31536000 + Math.round(Date.now() / 1000) }, {
auth: { username: this.username, password: this.apiKey }
})];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Genera un token
* @param expire valore in giorni alla di scadenza del token, default: un anno
*/
OpenApi.prototype.generateToken = function (scopes, expire, autoRenew) {
if (expire === void 0) { expire = 365; }
if (autoRenew === void 0) { autoRenew = true; }
return __awaiter(this, void 0, void 0, function () {
var body, res, err_2;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (typeof scopes === 'string') {
scopes = [scopes];
}
scopes = scopes.map(function (scope) {
if (!scope.match(/:/)) {
scope = '*:' + scope.replace('/', '') + '/*';
}
var url = OpenApi.splitScope(scope);
return scope.split(':', 1) + ":" + _this.prefix + url[0].replace(/^test.|dev./, '') + "/" + url[1];
});
_a.label = 1;
case 1:
_a.trys.push([1, 4, , 5]);
body = { scopes: scopes, expire: expire * 86400 };
return [4 /*yield*/, axios_1.default.post(this.getOauthUrl() + '/token', JSON.stringify(body), {
auth: { username: this.username, password: this.apiKey }
})];
case 2:
res = _a.sent();
return [4 /*yield*/, this.createClient(res.data.token, autoRenew)];
case 3:
_a.sent();
return [2 /*return*/, res.data.token];
case 4:
err_2 = _a.sent();
throw err_2;
case 5: return [2 /*return*/];
}
});
});
};
OpenApi.prototype.getOauthUrl = function () {
return 'https://' + this.prefix + 'oauth.altravia.com';
};
Object.defineProperty(OpenApi.prototype, "prefix", {
get: function () {
return this.environment === 'test' ? 'test.' : '';
},
enumerable: false,
configurable: true
});
OpenApi.splitScope = function (scope) {
return scope.split(':', 2)[1].split('/', 2);
};
OpenApi.init = function (environment, username, apiKey, token, autoRenew) {
if (autoRenew === void 0) { autoRenew = true; }
return __awaiter(this, void 0, void 0, function () {
var openapi;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
openapi = new OpenApi(environment, username, apiKey);
if (!token) return [3 /*break*/, 2];
return [4 /*yield*/, openapi.createClient(token, autoRenew)];
case 1:
_a.sent();
_a.label = 2;
case 2: return [2 /*return*/, openapi];
}
});
});
};
return OpenApi;
}());
exports.default = OpenApi;