@devopness/sdk-js
Version:
Devopness API JS/TS SDK - Painless essential DevOps to everyone
143 lines (142 loc) • 5.98 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.ApiBaseService = exports.Configuration = void 0;
const axios_1 = __importDefault(require("axios"));
const Exceptions_1 = require("../common/Exceptions");
class Configuration {
constructor(options) {
this.baseURL = "https://api.devopness.com";
this.apiKey = options.apiKey;
this.baseURL = options.baseURL || this.baseURL;
}
}
exports.Configuration = Configuration;
class ApiBaseService {
constructor() {
this.defaultAxiosSettings = {
timeout: 30000,
responseType: 'json',
headers: {
Accept: "application/json",
'Content-Type': "application/json"
},
withCredentials: false
};
if (ApiBaseService.configuration == undefined) {
throw new Exceptions_1.ArgumentNullException('configuration');
}
const settings = this.defaultAxiosSettings;
settings.baseURL = ApiBaseService.configuration.baseURL;
this.api = axios_1.default.create(settings);
this.setupAxios();
}
setupAxios() {
this.setUserAgent();
this.setupAxiosRequestInterceptors();
this.setupAxiosResponseInterceptors();
}
setUserAgent() {
// Firefox is fine with setting the 'User-Agent' header, but Chrome and Safari are not.
// As we don't want Chrome to raise piles of console logs with the error message:
// 'Refused to set unsafe header "User-Agent"', we then only set the UA header
// when the SDK is not being consumed from an app running on a browser foreground.
// i.e: node.js cli, node.js server side, web workers, ...
// if a window object is defined then we're very likely on a browser
// so we don't set a custom User-Agent header
const runningOnBrowserForeground = typeof window !== 'undefined';
if (!runningOnBrowserForeground) {
// Setting the `User-Agent` with SDK version so we can track SDK adoption
// through requests sent through it hitting our API servers
this.api.defaults.headers.common['User-Agent'] = `devopness-sdk-js/${ApiBaseService.SDK_VERSION}`;
}
}
setupAxiosRequestInterceptors() {
this.api.interceptors.request.use((config) => {
if (!config.headers) {
config.headers = {};
}
if (ApiBaseService._accessToken) {
config.headers.Authorization = `Bearer ${ApiBaseService._accessToken}`;
}
else {
delete config.headers.Authorization;
}
return config;
}, (error) => {
throw error;
});
}
setupAxiosResponseInterceptors() {
this.api.interceptors.response.use((response) => {
return response;
}, (error) => {
if (this.isTokenExpired(error.response)) {
// access_token is expired
ApiBaseService._onTokenExpired(ApiBaseService._accessToken);
return error.response;
}
if (error.response) {
// server responded, but with a status code other than 2xx
throw new Exceptions_1.ApiError(error);
}
else if (error.request) {
// no response received. e.g.: client lost internet connection after request has been sent
throw new Exceptions_1.NetworkError(error);
}
else {
// request wasn't sent. e.g: invalid IP/DNS provided as API base URL
throw new Exceptions_1.NetworkError(error);
}
});
}
static get accessToken() {
return ApiBaseService._accessToken;
}
static set accessToken(value) {
ApiBaseService._accessToken = value;
}
static set onTokenExpired(callback) {
ApiBaseService._onTokenExpired = callback;
}
isTokenExpired(response) {
var _a, _b;
if (!ApiBaseService.accessToken) {
return false;
}
const decodedToken = JSON.parse(Buffer.from((_b = (_a = ApiBaseService.accessToken) === null || _a === void 0 ? void 0 : _a.split(".")) === null || _b === void 0 ? void 0 : _b[1], "base64").toString());
return (response === null || response === void 0 ? void 0 : response.status) === 401 && decodedToken.exp < (new Date().getTime() / 1000);
}
baseURL() {
return this.api.defaults.baseURL ? this.api.defaults.baseURL : "";
}
post(endpoint, data) {
return __awaiter(this, void 0, void 0, function* () {
return this.api.post(endpoint, data);
});
}
put(endpoint, data) {
return __awaiter(this, void 0, void 0, function* () {
return this.api.put(endpoint, data);
});
}
delete(endpoint) {
return this.api.delete(endpoint);
}
get(endpoint) {
return this.api.get(endpoint);
}
}
exports.ApiBaseService = ApiBaseService;
ApiBaseService.SDK_VERSION = '0.0.0-development';
;