microstrategy
Version:
A node.js wrapper for the MicroStrategy REST API & Task API
1,303 lines (1,058 loc) • 227 kB
JavaScript
var mstrapi =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./lib/mstr.js");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./lib/mstr.js":
/*!*********************!*\
!*** ./lib/mstr.js ***!
\*********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = {
REST: __webpack_require__(/*! ./rest */ "./lib/rest.js"),
TaskAPI: __webpack_require__(/*! ./task */ "./lib/task.js")
};
/***/ }),
/***/ "./lib/rest.js":
/*!*********************!*\
!*** ./lib/rest.js ***!
\*********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const RestConnection = __webpack_require__(/*! ./util/RestConnection */ "./lib/util/RestConnection.js");
const AuthenticationAPI = __webpack_require__(/*! ./restAPIs/authentication */ "./lib/restAPIs/authentication.js");
const CubesAPI = __webpack_require__(/*! ./restAPIs/cubes */ "./lib/restAPIs/cubes.js");
const DatasetsAPI = __webpack_require__(/*! ./restAPIs/datasets */ "./lib/restAPIs/datasets.js");
const DossiersAndDocumentsAPI = __webpack_require__(/*! ./restAPIs/dossiersAndDocuments */ "./lib/restAPIs/dossiersAndDocuments.js");
const ObjectManagementAPI = __webpack_require__(/*! ./restAPIs/objectManagement */ "./lib/restAPIs/objectManagement.js");
const ReportsAPI = __webpack_require__(/*! ./restAPIs/reports */ "./lib/restAPIs/reports.js");
const UserManagementAPI = __webpack_require__(/*! ./restAPIs/userManagement */ "./lib/restAPIs/userManagement.js");
const LibraryAPI = __webpack_require__(/*! ./restAPIs/library */ "./lib/restAPIs/library.js");
module.exports = class MicroStrategyRESTAPI extends RestConnection {
constructor(...args) {
super(...args); // https://demo.microstrategy.com/MicroStrategyLibrary/api-docs/index.html#/Authentication
this.authentication = new AuthenticationAPI(this); // https://demo.microstrategy.com/MicroStrategyLibrary/api-docs/index.html#/Cubes
this.cubes = new CubesAPI(this); // https://demo.microstrategy.com/MicroStrategyLibrary/api-docs/index.html#/Datasets
this.datasets = new DatasetsAPI(this); // https://demo.microstrategy.com/MicroStrategyLibrary/api-docs/index.html#/Dossiers%20and%20Documents
this.dossiersAndDocuments = new DossiersAndDocumentsAPI(this); // https://demo.microstrategy.com/MicroStrategyLibrary/api-docs/index.html#/Library
this.library = new LibraryAPI(this); // https://demo.microstrategy.com/MicroStrategyLibrary/api-docs/index.html#/Object%20Management
this.objectManagement = new ObjectManagementAPI(this); // https://demo.microstrategy.com/MicroStrategyLibrary/api-docs/index.html#/Reports
this.reports = new ReportsAPI(this); // https://demo.microstrategy.com/MicroStrategyLibrary/api-docs/index.html#/User%20Management
this.userManagement = new UserManagementAPI(this);
return this;
}
/**
* Establish a session with MicroStrategy Library
*
* @param {Object} params
* @param {boolean} [shouldStoreSession=true]
* @param {boolean} [useStoredCredentials=false]
* @returns {Promise} resolving with session headers object
*/
login(...params) {
return this.authentication.login(...params);
}
/**
* Terminate a session with MicroStrategy Library - using the auth token as parameter
*
* @param {String|Object} token string or object with key 'X-MSTR-AuthToken'
* @returns {Promise} response object
*/
logout(...params) {
return this.authentication.logout(...params);
}
clearCookies() {
return this.authentication.clearCookies();
}
};
/***/ }),
/***/ "./lib/restAPIs/authentication.js":
/*!****************************************!*\
!*** ./lib/restAPIs/authentication.js ***!
\****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const assert = __webpack_require__(/*! assert */ "./node_modules/node-libs-browser/node_modules/assert/assert.js");
const assertParam = __webpack_require__(/*! ../util/assertParam */ "./lib/util/assertParam.js");
const RestUtil = __webpack_require__(/*! ../util/RestUtil */ "./lib/util/RestUtil.js");
const parseResponseSessionHeaders = (response = {}) => {
const headers = response.headers;
if (response.status != 204) {
throw {
status: response.status,
statusText: response.statusText || 'Login Failure',
headers: headers,
body: response.data
};
}
const sessionHeaders = {
'X-MSTR-AuthToken': headers['x-mstr-authtoken']
};
if (headers['set-cookie']) {
sessionHeaders['Cookie'] = headers['set-cookie'][0];
}
return sessionHeaders;
};
/*
https://demo.microstrategy.com/MicroStrategyLibrary/api-docs/index.html#/Authentication
*/
module.exports = class RestTopic extends RestUtil {
/**
* Establish a session with MicroStrategy Library
*
* @param {Object} params
* @param {boolean} [shouldStoreSession=true]
* @param {boolean} [useStoredCredentials=false]
* @returns {Promise} resolving with session headers object
*/
login(params, shouldStoreSession = true, useStoredCredentials = false) {
const savedParams = this.getSessionCredentials();
if (useStoredCredentials && savedParams) {
params = savedParams;
}
assertParam(params);
assertParam(params, 'username');
return this._makeRequest('auth/login', params, 'POST').then(response => {
const sessionHeaders = parseResponseSessionHeaders(response);
if (shouldStoreSession) {
this.setSessionCredentials(params);
this.setSessionHeaders(sessionHeaders);
}
return sessionHeaders;
});
}
/**
* Terminate a session with MicroStrategy Library - using the auth token as parameter
*
* @param {String|Object} token string or object with key 'X-MSTR-AuthToken'
* @returns response object
*/
logout(token, clearStoredCredentials = false) {
const endpoint = 'auth/logout';
const method = 'POST';
const body = false;
if (token) {
if (typeof token === 'string') {
return this._makeRequest(endpoint, body, method, {
'X-MSTR-AuthToken': token
});
}
assertParam(token);
assertParam(token, 'X-MSTR-AuthToken');
return this._makeRequest(endpoint, body, method, token);
}
return this._makeRequest(endpoint, body, method, this.getSessionHeaders()).then(result => {
if (result.status == 204) {
this.truncateStoredSession(clearStoredCredentials);
}
return result;
});
}
/**
* Clears any saved session state (token + cookies) from module memory.
* This will simply forget the session. This will not close the session.
* @param {String} clearStoredCredentials - defaults to true, any saved login credentials will be forgotten
*/
truncateStoredSession(clearStoredCredentials = true) {
this.setSessionHeaders();
clearStoredCredentials && this.setSessionCredentials();
}
/**
* Clears persisted cookies from memory
*/
clearCookies() {
return this.setSessionHeaders({
Cookie: ''
});
}
/**
* Validate an existing identity token. Requires an existing session (cookie + auth token)
* @param {String} identityToken
* @returns response object
*/
validateIdentityToken(identityToken) {
const endpoint = 'auth/identityToken';
const method = 'GET';
assertParam(identityToken);
const parameters = false;
const customHeaders = {
'X-MSTR-IdentityToken': identityToken
};
return this._makeRequest(endpoint, parameters, method, customHeaders).then(result => this.throwIfFailed(result, 200)).catch(e => this.throwExceptionResponse(e));
}
/**
* Create an identity token using an auth token
* @param {String} (optional) authToken - if not provided, will use existing session in module
* @returns {Promise} resolving identity token
*/
createIdentityToken(authToken = this.getAuthToken()) {
assert(authToken, 'No authToken provided and none found in-memory. Login first or provide auth token.');
const endpoint = 'auth/identityToken';
const method = 'POST';
const parameters = false;
const customHeaders = {
'X-MSTR-AuthToken': authToken
};
return this._makeRequest(endpoint, parameters, method, customHeaders).then(response => {
const headers = response.headers;
if (response.status != 201) {
throw {
status: response.status,
statusText: response.statusText || 'Failed to create token',
headers: headers,
body: response.data
};
}
return headers['x-mstr-identitytoken'];
}).catch(e => this.throwExceptionResponse(e));
}
/**
* Create/restore a REST API session using an identity token
* @param {String} identityToken
* @param {Boolean} automaticallyStoreSession - true by default - if set, session is stored in memory for easier use in other methods.
* @returns {Object} restored auth token & session cookie
*/
restoreIdentityToken(identityToken, automaticallyStoreSession = true) {
assert(identityToken, 'No identityToken provided - nothing to restore.');
const endpoint = 'auth/delegate';
const method = 'POST';
const parameters = {
loginMode: -1,
identityToken
};
return this._makeRequest(endpoint, parameters, method).then(response => {
const sessionHeaders = parseResponseSessionHeaders(response);
if (automaticallyStoreSession) {
this.setSessionHeaders(sessionHeaders);
}
return sessionHeaders;
}).catch(e => this.throwExceptionResponse(e));
}
/**
* Extend HTTP & Intelligence Server sessions by resetting timeouts.
*/
keepAlive() {
const endpoint = 'sessions';
const method = 'PUT';
return this._makeRequest(endpoint, false, method).then(result => this.throwIfFailed(result, 204)).catch(e => this.throwExceptionResponse(e));
}
/**
* Get summary state on current configuration session for authenticated user.
* @returns {Object} containing configuration session state
*/
getConfigurationSessionInfo() {
const endpoint = 'sessions';
const method = 'GET';
return this._makeRequest(endpoint, false, method).then(result => this.throwIfFailed(result, 200)).catch(e => this.throwExceptionResponse(e));
}
/**
* Get summary state on current project session for authenticated user.
* @param {String} projectId - (optional) provide as parameter or pre-set using restApi.setProjectId()
* @returns {Object} containing project session state
*/
getProjectSessionInfo(projectId) {
const endpoint = 'sessions/projectId';
const method = 'GET';
return this._makeRequest(endpoint, false, method, this.getProjectHeader(projectId)).then(result => this.throwIfFailed(result, 200)).catch(e => this.throwExceptionResponse(e));
}
/**
* Get information for the authenticated user.
* @returns {Object} containing currently authenticated metadata user
*/
getUserInfo() {
const endpoint = 'sessions/userInfo';
const method = 'GET';
return this._makeRequest(endpoint, false, method).then(result => this.throwIfFailed(result, 200)).catch(e => this.throwExceptionResponse(e));
}
/**
* Get a list of privileges for authenticated user
* @returns {Array} with a list of privilege objects
*/
getPrivilegesList() {
const endpoint = 'sessions/privileges';
const method = 'GET';
return this._makeRequest(endpoint, false, method).then(result => this.throwIfFailed(result, 200)).catch(e => this.throwExceptionResponse(e));
}
/**
* Get information on a specific privilege, by integer ID
* @param {Number} privilegeIdNumber - Number (or string containing number) representing privilege to query
* @returns {Object} with more information on specified privilege & scope of privilege for this session
*/
getPrivilegeInfo(privilegeIdNumber) {
assert(privilegeIdNumber, 'Privilege ID is missing');
const endpoint = `sessions/privileges/${privilegeIdNumber}`;
const method = 'GET';
return this._makeRequest(endpoint, false, method).then(result => this.throwIfFailed(result, 200)).catch(e => this.throwExceptionResponse(e));
}
};
/***/ }),
/***/ "./lib/restAPIs/cubes.js":
/*!*******************************!*\
!*** ./lib/restAPIs/cubes.js ***!
\*******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const assert = __webpack_require__(/*! assert */ "./node_modules/node-libs-browser/node_modules/assert/assert.js");
const RestUtil = __webpack_require__(/*! ../util/RestUtil */ "./lib/util/RestUtil.js");
const buildCommonQuery = __webpack_require__(/*! ../util/buildCommonQueryParams */ "./lib/util/buildCommonQueryParams.js");
/*
https://demo.microstrategy.com/MicroStrategyLibrary/api-docs/index.html#/Cubes
*/
module.exports = class RestTopic extends RestUtil {
_getBase() {
return 'cubes';
}
getCubeDefinition(cubeId) {
assert(cubeId, 'No cubeId provided');
return this._makeRequest(`v2/${this._getBase()}/${cubeId}`, false, 'GET', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200));
}
createCubeInstance(cubeId, body, offset, limit, fields) {
assert(cubeId, 'No cubeId provided');
const requestOpts = buildCommonQuery(fields, offset, limit);
return this._makeRequest(`v2/${this._getBase()}/${cubeId}/instances`, body, 'POST', this.getProjectHeader(), requestOpts).then(result => this.throwIfFailed(result, 200));
}
getInstanceResults(cubeId, instanceId, offset, limit, fields) {
assert(cubeId, 'No objectId provided');
assert(instanceId, 'No instanceId provided');
const requestOpts = buildCommonQuery(fields, offset, limit);
return this._makeRequest(`v2/${this._getBase()}/${cubeId}/instances/${instanceId}`, requestOpts, 'GET', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200));
}
publishCube(cubeId, fields) {
assert(cubeId, 'No cubeId provided');
const requestOpts = buildCommonQuery(fields);
return this._makeRequest(`${this._getBase()}/${cubeId}`, false, 'POST', this.getProjectHeader(), requestOpts).then(result => this.throwIfFailed(result, 202));
}
getStatus(cubeId) {
assert(cubeId, 'No cubeId provided');
return this._makeRequest(`${this._getBase()}/${cubeId}`, false, 'HEAD', this.getProjectHeader()).then(result => {
this.throwIfFailed(result, 200);
const headers = result.headers;
return headers['x-mstr-cubestatus'];
});
}
getCubesInfo(cubeIds, fields) {
assert(cubeIds, 'No cubeIds provided');
const requestOpts = buildCommonQuery(fields);
requestOpts.id = cubeIds;
return this._makeRequest(`${this._getBase()}`, requestOpts, 'GET', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200));
}
getCubeAttributeElement(cubeId, attributeId, baseFormIds, offset, limit, fields) {
assert(cubeId, 'No cubeId provided');
assert(attributeId, 'No attributeId provided');
const requestOpts = buildCommonQuery(fields, offset, limit);
if (baseFormIds) {
requestOpts.baseFormIds = baseFormIds;
}
return this._makeRequest(`${this._getBase()}/${cubeId}/attributes/${attributeId}/elements`, requestOpts, 'GET', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200));
}
getCubeInstanceAttributeElement(cubeId, instanceId, attributeId, searchPattern, offset, limit, fields) {
assert(cubeId, 'No cubeId provided');
assert(instanceId, 'No instanceId provided');
assert(attributeId, 'No attributeId provided');
const requestOpts = buildCommonQuery(fields, offset, limit);
if (searchPattern) {
requestOpts.searchPattern = searchPattern;
}
const endpoint = `${this._getBase()}/${cubeId}/instances/${instanceId}/attributes/${attributeId}/elements`;
return this._makeRequest(endpoint, requestOpts, 'GET', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200));
}
/**
* @deprecated Use v2 method instead (getCubeDefinition)
*/
getCubeDefinitionV1(cubeId) {
assert(cubeId, 'No cubeId provided');
return this._makeRequest(`${this._getBase()}/${cubeId}`, false, 'GET', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200));
}
/**
* @deprecated Use v2 method instead (createCubeInstance)
*/
createCubeInstanceV1(cubeId, body, offset, limit, fields) {
assert(cubeId, 'No cubeId provided');
const requestOpts = buildCommonQuery(fields, offset, limit);
return this._makeRequest(`${this._getBase()}/${cubeId}/instances`, body, 'POST', this.getProjectHeader(), requestOpts).then(result => this.throwIfFailed(result, 200));
}
/**
* @deprecated Use v2 method instead (getInstanceResults)
*/
getInstanceResultsV1(cubeId, instanceId, offset, limit, fields) {
assert(cubeId, 'No cubeId provided');
assert(instanceId, 'No instanceId provided');
const requestOpts = buildCommonQuery(fields, offset, limit);
return this._makeRequest(`${this._getBase()}/${cubeId}/instances/${instanceId}`, requestOpts, 'GET', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200));
}
};
/***/ }),
/***/ "./lib/restAPIs/datasets.js":
/*!**********************************!*\
!*** ./lib/restAPIs/datasets.js ***!
\**********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(Buffer) {const assert = __webpack_require__(/*! assert */ "./node_modules/node-libs-browser/node_modules/assert/assert.js");
const assertParam = __webpack_require__(/*! ../util/assertParam */ "./lib/util/assertParam.js");
const RestUtil = __webpack_require__(/*! ../util/RestUtil */ "./lib/util/RestUtil.js");
const buildCommonQuery = __webpack_require__(/*! ../util/buildCommonQueryParams */ "./lib/util/buildCommonQueryParams.js");
/*
https://demo.microstrategy.com/MicroStrategyLibrary/api-docs/index.html#/Datasets
*/
module.exports = class RestTopic extends RestUtil {
/**
* @private get base endpoint for this API category
* @returns {String} endpoint prefix
*/
_getBase() {
return 'datasets';
}
/**
* @private get base endpoint for UploadSessions functionality in this API category
* @param {String} datasetId - dataset (cube) ID that this session is connected to
* @returns {String} endpoint prefix
*/
_getUploadSessionBase(datasetId) {
return this._getBase() + '/' + datasetId + '/uploadSessions';
}
/**
* @public Get the definition of a specific MTDI dataset (single or multi-table).
*
* @param {String} datasetId (cube ID)
* @param {Array} fields (optional)
* @returns {Object} representing dataset definition
*/
getDatasetDefinition(datasetId, fields) {
assert(datasetId, 'No datasetId provided');
const queryParameter = buildCommonQuery(fields);
return this._makeRequest(`${this._getBase()}/${datasetId}`, queryParameter, 'GET', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200));
}
/**
* @public Create a structured single-table dataset. For complex or multi-table datasets, use UploadSessions. See createUploadSession().
* @param {Object} [newDatasetBody={}] - Dataset creation info - see REST API documentation
* @param {Array} fields (optional)
* @returns {Object} { datasetId, name, tables[] }
*/
createDataset(newDatasetBody = {}, fields) {
assertParam(newDatasetBody);
assertParam(newDatasetBody, 'name');
assertParam(newDatasetBody, 'tables');
const queryParameter = buildCommonQuery(fields);
return this._makeRequest(this._getBase(), newDatasetBody, 'POST', this.getProjectHeader(), queryParameter).then(result => this.throwIfFailed(result, 200));
}
/**
* @public Create the definition of a dataset containing one or more tables, for use with an UploadSession.
*
* @param {Object} [newDatasetBody={}]
* @param {Array} fields (optional)
*/
createMultiTableDataset(newDatasetBody = {}, fields) {
assertParam(newDatasetBody);
assertParam(newDatasetBody, 'name');
assertParam(newDatasetBody, 'tables');
const queryParameter = buildCommonQuery(fields);
return this._makeRequest(`${this._getBase()}/models`, newDatasetBody, 'POST', this.getProjectHeader(), queryParameter).then(result => this.throwIfFailed(result, 200)).catch(e => this.throwExceptionResponse(e));
}
/**
* @public Update data in a single-table dataset created via this API.
*
* @param {String} datasetId (cube ID)
* @param {String} tableId - table ID or Name
* @param {Object} datasetBody - Dataset update info - see REST API documentation
* @param {string} [updatePolicy='Replace'] - Update operation type: Add, Update, Upsert, Replace
* @param {Array} fields (optional)
* @returns {Promise} resolving on success
*/
updateDataset(datasetId, tableId, datasetBody, updatePolicy = 'Replace', fields) {
assert(datasetId, 'No datasetId provided');
assert(tableId, 'No tableId provided');
assertParam(datasetBody);
assertParam(datasetBody, 'name');
assertParam(datasetBody, 'data');
const projectHeaders = this.getProjectHeader();
const headers = {
updatePolicy: updatePolicy,
...projectHeaders
};
const queryParameter = buildCommonQuery(fields);
return this._makeRequest(this._getBase() + `/${datasetId}/tables/${tableId}`, datasetBody, 'PATCH', headers, queryParameter).then(result => this.throwIfFailed(result, 200));
}
/**
* @public Create a multi-table dataset upload session and provide formatting information for the data that is to be uploaded to the Intelligence Server.
*
* @param {String} datasetId - ID of the existing dataset. If not existing yet, use DatasetAPI.createDataset()
* @param {Object} tablesFormatting - object representation of table formatting, with update policy for this upload session
* @returns {String} uploadSessionID
*/
createUploadSession(datasetId, tablesFormatting) {
assert(datasetId, 'No datasetId provided');
assert(tablesFormatting, 'No tables formatting provided');
return this._makeRequest(this._getUploadSessionBase(datasetId), tablesFormatting, 'POST', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200)).then(result => result.uploadSessionId || result).catch(e => this.throwExceptionResponse(e));
}
/**
* @public Push data into upload session.
*
* @param {String} datasetId
* @param {String} uploadSessionId
* @param {String} tableName - name of this table that this data manipulation is intended for
* @param {String|Number} index - slice index (starts at 1, increase with each consequent request for multiple data batches)
* @param {Object|String} data - data to ADD/UPDATE/UPSERT/REPLACE in this action
* @param {Boolean} [encodeAutomatically=true] - (optional) - if true, data will be converted from JSON to base64 encoding automatically
*/
uploadDataToUploadSession(datasetId, uploadSessionId, tableName, index = 1, rawData, encodeAutomatically = true) {
assert(datasetId, 'No datasetId provided');
assert(uploadSessionId, 'No uploadSessionId provided');
assert(tableName, 'No tableName provided');
assert(index, 'No index provided');
assert(rawData, 'No rawData provided');
const uploadSessionBasePath = this._getUploadSessionBase(datasetId);
const endpoint = `${uploadSessionBasePath}/${uploadSessionId}`;
const dataAsString = typeof rawData == 'string' ? rawData : JSON.stringify(rawData);
const base64encodedData = !encodeAutomatically ? rawData : Buffer.from(dataAsString).toString('base64');
const requestBody = {
tableName,
index,
data: base64encodedData
};
return this._makeRequest(endpoint, requestBody, 'PUT', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200)).catch(e => this.throwExceptionResponse(e));
}
/**
* @public Delete a specific multi-tavble dataset upload session and cancel publication.
* If upload session has not been published, all dataset operations for upload session will be cancelled and the uploaded data will be discarded.
*
* @param {String} datasetId
* @param {String} uploadSessionId
*/
deleteUploadSession(datasetId, uploadSessionId) {
assert(datasetId, 'No datasetId provided');
assert(uploadSessionId, 'No uploadSessionId provided');
const uploadSessionBasePath = this._getUploadSessionBase(datasetId);
const endpoint = `${uploadSessionBasePath}/${uploadSessionId}`;
return this._makeRequest(endpoint, false, 'DELETE', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200)).catch(e => this.throwExceptionResponse(e));
}
/**
* @public Publish a specific multi-table dataset using data uplaoded to the Intelligence Server.
* Use after adding data to existing upload session.
*
* @param {String} datasetId
* @param {String} uploadSessionId
* @returns {Promise} - throws on failure, resolves on succses. Use getUploadSessionStatus() to poll publish status.
*/
publishUploadSessionDataset(datasetId, uploadSessionId) {
assert(datasetId, 'No datasetId provided');
assert(uploadSessionId, 'No uploadSessionId provided');
const uploadSessionBasePath = this._getUploadSessionBase(datasetId);
const endpoint = `${uploadSessionBasePath}/${uploadSessionId}/publish`;
return this._makeRequest(endpoint, false, 'POST', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200)).catch(e => this.throwExceptionResponse(e));
}
/**
* @public Get status of multi-table dataset operation, after uploading and publishing. Use after publishUploadSession().
*
* @param {String} datasetId
* @param {String} uploadSessionId
* @returns {Object} - { status, message }
*/
getUploadSessionStatus(datasetId, uploadSessionId) {
assert(datasetId, 'No datasetId provided');
assert(uploadSessionId, 'No uploadSessionId provided');
const uploadSessionBasePath = this._getUploadSessionBase(datasetId);
const endpoint = `${uploadSessionBasePath}/${uploadSessionId}/publishStatus`;
return this._makeRequest(endpoint, false, 'GET', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200)).catch(e => this.throwExceptionResponse(e));
}
};
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/buffer/index.js */ "./node_modules/buffer/index.js").Buffer))
/***/ }),
/***/ "./lib/restAPIs/dossiersAndDocuments.js":
/*!**********************************************!*\
!*** ./lib/restAPIs/dossiersAndDocuments.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const assert = __webpack_require__(/*! assert */ "./node_modules/node-libs-browser/node_modules/assert/assert.js");
const assertParam = __webpack_require__(/*! ../util/assertParam */ "./lib/util/assertParam.js");
const RestUtil = __webpack_require__(/*! ../util/RestUtil */ "./lib/util/RestUtil.js");
/*
https://demo.microstrategy.com/MicroStrategyLibrary/api-docs/index.html#/Dossiers%20and%20Documents
*/
module.exports = class RestTopic extends RestUtil {
_getBase() {
return 'dossiers';
}
_getV2Base() {
return 'v2/dossiers';
}
/**
* Get hierarchy of a dossier, uses predecessor to v2 API
*
* @param {*} dossierId
* @returns
*/
getDossierDefinition(dossierId) {
assert(dossierId, 'No dossierId provided');
return this._makeRequest(`${this._getV2Base()}/${dossierId}/definition`, false, 'GET', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200)).catch(e => this.throwExceptionResponse(e));
}
/**
* @deprecated Get hierarchy of a dossier, uses predecessor to v2 API
*
* @param {string} dossierId
* @returns
*/
getDossierDefinitionOld(dossierId) {
assert(dossierId, 'No dossierId provided');
return this._makeRequest(`${this._getBase()}/${dossierId}/definition`, false, 'GET', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200)).catch(e => this.throwExceptionResponse(e));
}
/**
* Execute a specific dossier and create an instance of the dossier
*
* @param {string} dossierId
* @param {object} body (optional)
* @param {boolean} asyncMode (optional)
* @returns
*/
createDossierInstance(dossierId, body, asyncMode) {
assert(dossierId, 'No dossierId provided');
const customHeaders = this.getProjectHeader();
if (asyncMode) {
customHeaders['X-MSTR-AsyncMode'] = true;
}
return this._makeRequest(`${this._getBase()}/${dossierId}/instances`, body, 'POST', customHeaders).then(result => this.throwIfFailed(result, 201)).catch(e => this.throwExceptionResponse(e));
}
/**
* Get the hierarchy of a specific dossier in a specific project from instance.
*
* @param {string} dossierId
* @param {string} instanceId
* @returns {Promise} resolving object representing dossier hierarchy
*/
getDossierInstanceDefinition(dossierId, instanceId) {
assert(dossierId, 'No dossierId provided');
assert(instanceId, 'No instanceId provided');
return this._makeRequest(`${this._getV2Base()}/${dossierId}/instances/${instanceId}/definition`, false, 'GET', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200)).catch(e => this.throwExceptionResponse(e));
}
/**
* Get the definition and data result of a grid/graph visuaization in a specific dossier & project.
*
* @param {string} dossierId
* @param {string} instanceId
* @param {string} chapterKey
* @param {string} visualizationKey
* @returns
*/
getDossierVisualization(dossierId, instanceId, chapterKey, visualizationKey) {
assert(dossierId, 'No dossierId provided');
assert(instanceId, 'No instanceId provided');
assert(chapterKey, 'No chapterKey provided');
assert(visualizationKey, 'No visualizationKey provided');
const endpoint = `${this._getV2Base()}/${dossierId}/instances/${instanceId}/chapters/${chapterKey}/visualizations/${visualizationKey}`;
return this._makeRequest(endpoint, false, 'GET', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200)).catch(e => this.throwExceptionResponse(e));
}
};
/***/ }),
/***/ "./lib/restAPIs/library.js":
/*!*********************************!*\
!*** ./lib/restAPIs/library.js ***!
\*********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const assert = __webpack_require__(/*! assert */ "./node_modules/node-libs-browser/node_modules/assert/assert.js");
const assertParam = __webpack_require__(/*! ../util/assertParam */ "./lib/util/assertParam.js");
const RestUtil = __webpack_require__(/*! ../util/RestUtil */ "./lib/util/RestUtil.js");
const buildCommonQuery = __webpack_require__(/*! ../util/buildCommonQueryParams */ "./lib/util/buildCommonQueryParams.js");
module.exports = class RestTopic extends RestUtil {
/**
* Get base endpoint for this API category
*/
_getBase() {
return 'library';
}
/**
* Return object representing the library for the authenticated user.
* @param {string} outputFlag - Filtered output. DEAFULT = include everything, FILTER_TOC = filter out chapters and pages.
* @param {string} fields - Fields to be included in the result
* @return {Object} Library for the authenticated user
*/
getLibrary(outputFlag = 'DEFAULT', fields = '') {
const queryParameter = buildCommonQuery(fields);
queryParameter.outputFlag = outputFlag;
return this._makeRequest(this._getBase(), queryParameter, 'GET').then(result => this.throwIfFailed(result, 200));
}
/**
* Publish an object (document or dossier) in project defined by projectID.
* Information about object to publish and recipient are detailed in object 'publishInfo'.
* https://demo.microstrategy.com/MicroStrategyLibrary/api-docs/index.html#/Library/publishObject
* @param {Object} publishInfo - Information of the object to publish
* @param {string} projectID - Project ID
*/
publishObject(publishInfo, projectID) {
assert(publishInfo, 'No publishInfo provided');
const customHeaders = this.getProjectHeader(projectID);
return this._makeRequest(this._getBase(), publishInfo, 'POST', customHeaders).then(result => this.throwIfFailed(result, 204));
}
/**
* Return object (document or dossier) identified by 'objectId' from project identified by 'projectId'
* @param {string} projectId
* @param {string} documentId
* @param {string} fields - Fields to be included in the result. i.e. 'id,elements'
* @returns {Object} - Representing the object
*/
getObject(objectId, projectId, fields = '') {
const queryParameter = buildCommonQuery(fields);
const endpoint = `${this._getBase()}/${objectId}`;
const customHeaders = this.getProjectHeader(projectId);
return this._makeRequest(endpoint, queryParameter, 'GET', customHeaders).then(result => this.throwIfFailed(result, 200));
}
/**
* Delete an object (dossier or document) identified by 'objectId' from project identified by 'projectId'
* @param {string} projectId
* @param {string} objectId
*/
deleteObject(objectId, projectId) {
const endpoint = `${this._getBase()}/${objectId}`;
const queryParameter = buildCommonQuery();
const customHeaders = this.getProjectHeader(projectId);
return this._makeRequest(endpoint, queryParameter, 'DELETE', customHeaders).then(result => this.throwIfFailed(result, 204));
}
/**
* Delete object (dossier or document) identified by 'objectId' from project identified by 'projectId' of user identified by 'userId'
* @param {string} projectId
* @param {string} objectId
* @param {string} userId
*/
deleteUserObject(objectId, userId, projectId) {
assert(objectId, 'No objectId provided');
assert(userId, 'No userId provided');
const endpoint = `${this._getBase()}/${objectId}/recipients/${userId}`;
const queryParameter = buildCommonQuery();
const customHeaders = this.getProjectHeader(projectId);
return this._makeRequest(endpoint, queryParameter, 'DELETE', customHeaders).then(result => this.throwIfFailed(result, 204));
}
};
/***/ }),
/***/ "./lib/restAPIs/objectManagement.js":
/*!******************************************!*\
!*** ./lib/restAPIs/objectManagement.js ***!
\******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const assert = __webpack_require__(/*! assert */ "./node_modules/node-libs-browser/node_modules/assert/assert.js");
const RestUtil = __webpack_require__(/*! ../util/RestUtil */ "./lib/util/RestUtil.js");
const buildCommonQuery = __webpack_require__(/*! ../util/buildCommonQueryParams */ "./lib/util/buildCommonQueryParams.js");
module.exports = class RestTopic extends RestUtil {
_getBase() {
return 'objects';
}
getObject(objectId, type, fields) {
assert(objectId, 'No objectId provided');
assert(type, 'No type provided');
const queryParameter = buildCommonQuery(fields);
queryParameter.type = type;
return this._makeRequest(`${this._getBase()}/${objectId}`, queryParameter, 'GET', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200));
}
updateObject(objectId, type, objectsBody, flags, fields) {
assert(objectId, 'No objectId provided');
assert(type, 'No type provided');
assert(objectsBody, 'No objectsBody provided');
const queryParameter = buildCommonQuery(fields);
queryParameter.type = type;
if (flags) {
queryParameter.flags = flags;
}
return this._makeRequest(`${this._getBase()}/${objectId}`, objectsBody, 'PUT', this.getProjectHeader(), queryParameter).then(result => this.throwIfFailed(result, 200));
}
copyObject(objectId, type, objectsBody, fields) {
assert(objectId, 'No objectId provided');
assert(type, 'No type provided');
assert(objectsBody, 'No objectsBody provided');
const queryParameter = buildCommonQuery(fields);
queryParameter.type = type;
return this._makeRequest(`${this._getBase()}/${objectId}/copy`, objectsBody, 'POST', this.getProjectHeader(), queryParameter).then(result => this.throwIfFailed(result, 201));
}
deleteObject(objectId, type) {
assert(objectId, 'No objectId provided');
assert(type, 'No type provided');
const queryParameter = {
type: type
};
return this._makeRequest(`${this._getBase()}/${objectId}`, {}, 'DELETE', this.getProjectHeader(), queryParameter).then(result => this.throwIfFailed(result, 204));
}
certifyObject(objectId, type, certify) {
assert(objectId, 'No objectId provided');
assert(type, 'No type provided');
assert(certify, 'No certify value provided');
const queryParameter = {
type: type,
certify: certify
};
return this._makeRequest(`${this._getBase()}/${objectId}/certify`, {}, 'PUT', this.getProjectHeader(), queryParameter).then(result => this.throwIfFailed(result, 200));
}
getRecommendations(objectId, offset, limit, fields) {
assert(objectId, 'No objectId provided');
const queryParameter = buildCommonQuery(fields, offset, limit);
return this._makeRequest(`${this._getBase()}/${objectId}/recommendations`, queryParameter, 'GET', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200));
}
};
/***/ }),
/***/ "./lib/restAPIs/reports.js":
/*!*********************************!*\
!*** ./lib/restAPIs/reports.js ***!
\*********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const assert = __webpack_require__(/*! assert */ "./node_modules/node-libs-browser/node_modules/assert/assert.js");
const RestUtil = __webpack_require__(/*! ../util/RestUtil */ "./lib/util/RestUtil.js");
const buildCommonQuery = __webpack_require__(/*! ../util/buildCommonQueryParams */ "./lib/util/buildCommonQueryParams.js");
/*
https://demo.microstrategy.com/MicroStrategyLibrary/api-docs/index.html#/Reports
*/
module.exports = class RestTopic extends RestUtil {
_getBase() {
return 'reports';
}
getReportDefinition(objectId) {
assert(objectId, 'No objectID provided');
return this._makeRequest(`v2/${this._getBase()}/${objectId}`, false, 'GET', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200));
}
createReportInstance(objectId, body, offset, limit, fields) {
assert(objectId, 'No objectId provided');
const requestOpts = buildCommonQuery(fields, offset, limit);
return this._makeRequest(`v2/${this._getBase()}/${objectId}/instances`, body, 'POST', this.getProjectHeader(), requestOpts).then(result => this.throwIfFailed(result, 200));
}
getReportInstance(objectId, instanceId, offset, limit, fields) {
assert(objectId, 'No objectId provided');
assert(instanceId, 'No instanceId provided');
const requestOpts = buildCommonQuery(fields, offset, limit);
return this._makeRequest(`v2/${this._getBase()}/${objectId}/instances/${instanceId}`, requestOpts, 'GET', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200));
}
updateReportInstance(objectId, instanceId, requestBody, offset, limit, fields) {
assert(objectId, 'No objectId provided');
assert(instanceId, 'No instanceId provided');
assert(requestBody, 'No requestBody provided');
const requestOpts = buildCommonQuery(fields, offset, limit);
const endpoint = `v2/${this._getBase()}/${objectId}/instances/${instanceId}`;
return this._makeRequest(endpoint, requestBody, 'PUT', this.getProjectHeader(), requestOpts).then(result => this.throwIfFailed(result, 200));
}
/**
* @deprecated Use v2 method instead (getReportDefinition)
*/
getReportDefinitionV1(objectId) {
assert(objectId, 'No objectID provided');
return this._makeRequest(`${this._getBase()}/${objectId}`, false, 'GET', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200));
}
/**
* @deprecated Use v2 method instead (createReportInstance)
*/
createReportInstanceV1(objectId, body, offset, limit, fields) {
assert(objectId, 'No objectId provided');
const requestOpts = buildCommonQuery(fields, offset, limit);
return this._makeRequest(`${this._getBase()}/${objectId}/instances`, body, 'POST', this.getProjectHeader(), requestOpts).then(result => this.throwIfFailed(result, 200));
}
/**
* @deprecated Use v2 method instead (getReportInstance)
*/
getReportInstanceV1(objectId, instanceId, offset, limit, fields) {
assert(objectId, 'No objectId provided');
assert(instanceId, 'No instanceId provided');
const requestOpts = buildCommonQuery(fields, offset, limit);
return this._makeRequest(`${this._getBase()}/${objectId}/instances/${instanceId}`, requestOpts, 'GET', this.getProjectHeader()).then(result => this.throwIfFailed(result, 200));
}
};
/***/ }),
/***/ "./lib/restAPIs/userManagement.js":
/*!****************************************!*\
!*** ./lib/restAPIs/userManagement.js ***!
\****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const assert = __webpack_require__(/*! assert */ "./node_modules/node-libs-browser/node_modules/assert/assert.js");
const assertParam = __webpack_require__(/*! ../util/assertParam */ "./lib/util/assertParam.js");
const RestUtil = __webpack_require__(/*! ../util/RestUtil */ "./lib/util/RestUtil.js");
const buildCommonQuery = __webpack_require__(/*! ../util/buildCommonQueryParams */ "./lib/util/buildCommonQueryParams.js");
module.exports = class RestTopic extends RestUtil {
_getBase() {
return 'users';
}
/**
* @public Get information for a specific set of users.
* @param {string} nameBegins - Characters that the user name must begin with
* @param {string} abbreviationBegins - Characters that the user abbreviation must begin with
* @param {number} offset - Used to control paging behaviour
* @param {number} limit - Maximum number of items returned
* @param {string} fields - Top level fields to be included in the response
*/
getUsers(nameBegins, abbreviationBegins, offset = 0, limit = -1, fields) {
const queryParameter = buildCommonQuery(fields, offset, limit);
if (nameBegins) {
queryParameter.nameBegins = nameBegins;
}
if (abbreviationBegins) {
queryParameter.abbreviationBegins = abbreviationBegins;
}
return this._makeRequest(this._getBase(), queryParameter, 'GET').then(result => this.throwIfFailed(result, 200));
}
/**
* @public Get info for a specific user
* @param {string} userId - User ID
* @param {string} fields - Top level fields to be included in the response
* @return {Object} Information from user identified by userId
*/
getUser(userId, fields) {
assert(userId, 'No userId provided');
const queryParameter = buildCommonQuery(fields);
return this._makeRequest(`${this._getBase()}/${userId}`, queryParameter, 'GET').then(result => this.throwIfFailed(result, 200));
}
/**
* @public Create a new user
* @param {Object} newUserBody - User information
* @param {string} fields - Top level fields to be included in the response
*/
createUser(newUserBody = {}, fields) {
assertParam(newUserBody);
assertParam(newUserBody, 'username');
assertParam(newUserBody, 'fullName');
const queryParameter = buildCommonQuery(fields);
return this._makeRequest(this._getBase(), newUserBody, 'POST', false, queryParameter).then(result => this.throwIfFailed(result, 201));
}
/**
* @public Delete user for a specific ID
* @param {string} userId - User ID
*/
deleteUser(userId) {
assert(userId, 'No userId provided');
return this._makeRequest(this._getBase() + `/${userId}`, false, 'DELETE').then(result => this.throwIfFailed(result, 204));
}
/**
* @public Update specific information for the user identified by userId
* @param {string} userId - User ID
* @param {Object} userBody - User update information
* @param {string} fields - Top level fields to be included in the response
*/
updateUser(userId, userBody, fields) {
assert(userId, 'No userId provided');
assertParam(userBody, 'operationList'); // Validate each object in operation list
let opList = userBody.operationList;
for (let i = 0; i < opList.length; i++) {
assertParam(opList[i], 'op');
assertParam(opList[i], 'path');
assertParam(opList[i], 'value');
}
const queryParameter = buildCommonQuery(fields);
return this._makeRequest(this._getBase() + `/${userId}`, userBody, 'PATCH', false, queryParameter).then(result => this.throwIfFailed(result, 200));
}
};
/***/ }),
/***/ "./lib/task.js":
/*!*********************!*\
!*** ./lib/task.js ***!
\*********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const TaskConnection = __webpack_require__(/*! ./util/TaskConnection */ "./lib/util/TaskConnection.js");
module.exports = class MicroStrategyTaskAPI extends TaskConnection {
constructor(...args) {
super(...args);
return this;
}
/**
* Execute any task via the MicroStrategy Web Task API
*
* @param {String} taskId
* @param {Object} [parameters={}] Key:value list of parameters
* @param {String} [taskEnv='xhr']
* @param {String} [taskContentType='json']
* @param {String} taskProcUrl - (optional) Override taskAPI url. Defaults to taskProcUrl defined on class init.
* @returns {Promise} Parsed response
*/
executeTask(taskId, parameters = {}, taskEnv = 'xhr', taskContentType = 'json', taskProcUrl) {
return this._executeTask(taskId, parameters, taskEnv, taskContentType, taskProcUrl);
}
async login() {
const taskParameters = {
server: 'aps-tsiebler-vm',
project: 'MicroStrategy Tutorial',
userid: 'administrator',
password: ''
};
try {
const res = await this._executeTask('login', taskParameters);
console.log('taskres: ', res);
} catch (E) {