electerm-sync
Version:
electerm sync API wrapper.
109 lines (107 loc) • 3.28 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HTTPError = void 0;
// based on tyler's work: https://github.com/tylerlong/ringcentral-js-concise
const axios_1 = __importDefault(require("axios"));
const jsonwebtoken_1 = require("jsonwebtoken");
const version = process.env.version || '';
class HTTPError extends Error {
constructor(status, statusText, data, config) {
super(`status: ${status}
statusText: ${statusText}
data: ${JSON.stringify(data, null, 2)}
config: ${JSON.stringify(config, null, 2)}`);
this.status = status;
this.statusText = statusText;
this.data = data;
this.config = config;
}
}
exports.HTTPError = HTTPError;
class ElectermSync {
constructor(str, userAgentHeader = `electerm-sync/v${version}`) {
const [token, server, userId = '', algorithm = 'HS256'] = str.split('####');
this.token = token;
this.server = server;
this.userId = userId;
this.algorithm = algorithm;
this.userAgentHeader = userAgentHeader;
this._axios = axios_1.default.create();
const request = this._axios.request.bind(this._axios);
this._axios.request = async (config) => {
try {
return await request(config);
}
catch (e) {
if (e.response) {
throw new HTTPError(e.response.status, e.response.statusText, e.response.data, e.response.config);
}
else {
throw e;
}
}
};
}
async request(config) {
return await this._axios.request({
...config,
headers: this._patchHeaders(config.headers)
});
}
async create(data, conf) {
return await this.request({
url: this.server,
method: 'PUT',
data,
...conf
});
}
async update(userId, data, conf) {
this.userId = userId;
return await this.request({
url: this.server,
method: 'PUT',
data,
...conf
});
}
async getOne(userId, conf) {
this.userId = userId;
return await this.request({
url: this.server,
method: 'GET',
...conf
});
}
async test(conf) {
return await this.request({
url: this.server,
method: 'POST',
...conf
});
}
_patchHeaders(headers = {}) {
return {
'Content-Type': 'application/json',
...this._authHeader(),
'X-User-Agent': this.userAgentHeader,
...headers
};
}
_authHeader() {
const tk = this.userId !== ''
? (0, jsonwebtoken_1.sign)({
id: this.userId,
exp: Date.now() + 1000000
}, this.token, { algorithm: this.algorithm })
: this.token;
return {
Authorization: `Bearer ${tk}`
};
}
}
exports.default = ElectermSync;
module.exports = ElectermSync;