@zendesk/zcli-core
Version:
ZCLI core libraries and services
52 lines (51 loc) • 2.62 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.requestAPI = exports.createRequestConfig = void 0;
const axios_1 = require("axios");
const secureStore_1 = require("./secureStore");
const auth_1 = require("./auth");
const errors_1 = require("@oclif/core/lib/errors");
const chalk = require("chalk");
const env_1 = require("./env");
const requestUtils_1 = require("./requestUtils");
const MSG_ENV_OR_LOGIN = 'Set the following environment variables: ZENDESK_SUBDOMAIN, ZENDESK_EMAIL, ZENDESK_API_TOKEN. Or try logging in via `zcli login -i`';
const ERR_AUTH_FAILED = `Authorization failed. ${MSG_ENV_OR_LOGIN}`;
const ERR_ENV_SUBDOMAIN_NOT_FOUND = `No subdomain found. ${MSG_ENV_OR_LOGIN}`;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const createRequestConfig = async (url, options = {}) => {
let auth;
if ((0, env_1.varExists)(env_1.EnvVars.SUBDOMAIN, env_1.EnvVars.OAUTH_TOKEN) ||
(0, env_1.varExists)(env_1.EnvVars.SUBDOMAIN, env_1.EnvVars.EMAIL, env_1.EnvVars.API_TOKEN)) {
auth = new auth_1.default();
}
else {
const secureStore = new secureStore_1.default();
await secureStore.loadKeytar();
auth = new auth_1.default({ secureStore });
}
const [authToken, profileSubdomain, profileDomain] = await Promise.all([auth.getAuthorizationToken(), (0, requestUtils_1.getSubdomain)(auth), (0, requestUtils_1.getDomain)(auth)]);
if (!authToken)
throw new errors_1.CLIError(chalk.red(ERR_AUTH_FAILED));
const subdomain = process.env[env_1.EnvVars.SUBDOMAIN] || profileSubdomain;
if (!subdomain)
throw new errors_1.CLIError(chalk.red(ERR_ENV_SUBDOMAIN_NOT_FOUND));
const domain = process.env[env_1.EnvVars.SUBDOMAIN] ? process.env[env_1.EnvVars.DOMAIN] : profileDomain;
if (options.headers) {
options.headers = Object.assign({ Authorization: authToken }, options.headers);
}
else {
options.headers = { Authorization: authToken };
}
const baseURL = (0, requestUtils_1.getBaseUrl)(subdomain, domain);
return Object.assign({ baseURL,
url, validateStatus: function (status) {
return status < 500;
} }, options);
};
exports.createRequestConfig = createRequestConfig;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const requestAPI = async (url, options = {}, json = false) => {
const requestConfig = await (0, exports.createRequestConfig)(url, options);
return axios_1.default.request(Object.assign(Object.assign({}, requestConfig), { adapter: 'fetch' }));
};
exports.requestAPI = requestAPI;