UNPKG

d2-ui

Version:
281 lines (226 loc) 9.54 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.getManifest = getManifest; exports.getUserSettings = getUserSettings; exports.init = init; exports.getInstance = getInstance; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } } var _libUtils = require('./lib/utils'); var _loggerLogger = require('./logger/Logger'); var _loggerLogger2 = _interopRequireDefault(_loggerLogger); var _modelModels = require('./model/models'); var _modelModels2 = _interopRequireDefault(_modelModels); var _apiApi = require('./api/Api'); var _apiApi2 = _interopRequireDefault(_apiApi); var _systemSystem = require('./system/System'); var _systemSystem2 = _interopRequireDefault(_systemSystem); var _i18nI18n = require('./i18n/I18n'); var _i18nI18n2 = _interopRequireDefault(_i18nI18n); var _config = require('./config'); var _config2 = _interopRequireDefault(_config); var _currentUserCurrentUser = require('./current-user/CurrentUser'); var _currentUserCurrentUser2 = _interopRequireDefault(_currentUserCurrentUser); require('whatwg-fetch'); var firstRun = true; var deferredD2Init = _libUtils.Deferred.create(); var preInitConfig = _config2['default'].create(); function getManifest(url) { var api = new _apiApi2['default'](); api.setBaseUrl(''); var manifestUtilities = { getBaseUrl: function getBaseUrl() { return this.activities.dhis.href; } }; return api.get('' + url).then(function (manifest) { return Object.assign({}, manifest, manifestUtilities); }); } /** * @function getUserSettings * * @returns {Promise} A promise to the current user settings * * @description * The object that is the result of the promise will have the following properties * ```js * { * "uiLocale": "en" // The users locale, that can be used for translations) * } * ``` */ function getUserSettings() { var api = _apiApi2['default'].getApi(); if (preInitConfig.baseUrl && firstRun) { api.setBaseUrl(preInitConfig.baseUrl); } return api.get('userSettings'); } function getModelRequests(api) { var schemaNames = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1]; var fieldsForSchemas = ['apiEndpoint,name,authorities,singular,plural,shareable,metadata,klass,identifiableObject,properties[href', 'writable,collection,collectionName,name,propertyType,persisted,required,min,max,ordered,unique,constants', 'owner,itemPropertyType]'].join(','); var modelRequests = []; var loadSchemaForName = function loadSchemaForName(schemaName) { return api.get('schemas/' + schemaName, { fields: fieldsForSchemas }); }; if (schemaNames.length > 0) { var individualSchemaRequests = schemaNames.map(loadSchemaForName); var schemasPromise = Promise.all(individualSchemaRequests).then(function (schemas) { return { schemas: schemas }; }); modelRequests.push(schemasPromise); } else { // Used as a source to generate the models. modelRequests.push(api.get('schemas', { fields: fieldsForSchemas })); } // Used to add the dynamic attributes to the models that should have them. modelRequests.push(api.get('attributes', { fields: ':all,optionSet[:all,options[:all]]', paging: false })); return modelRequests; } /** * @function init * * @param {Object} initConfig Configuration object that will be used to configure to define D2 Setting. * See the description for more information on the available settings. * @returns {Promise} A promise that resolves with the intialized d2 object. Which is an object that exposes `model`, `models` and `Api` * * @description * Init function that used to initialise D2. This will load the schemas from the DHIS2 api and configure your D2 instance. * * The `config` object that can be passed into D2 can have the following properties: * * baseUrl: Set this when the url is something different then `/api`. If you are running your dhis instance in a subdirectory of the actual domain * for example http://localhost/dhis/ you should set the base url to `/dhis/api` * * ```js * import init from 'd2'; * * init({baseUrl: '/dhis/api'}) * .then((d2) => { * console.log(d2.model.dataElement.list()); * }); * ``` */ function init(initConfig) { var api = _apiApi2['default'].getApi(); var logger = _loggerLogger2['default'].getLogger(); var config = _config2['default'].create(preInitConfig, initConfig); var d2 = { models: undefined, model: _modelModels2['default'], Api: _apiApi2['default'], system: _systemSystem2['default'].getSystem(), i18n: _i18nI18n2['default'].getI18n() }; // Process the config in a the config class to keep all config calls together. _config2['default'].processConfigForD2(config, d2); // Because when importing the getInstance method in dependencies the getInstance could run before // init we have to resolve the current promise on first run and for consecutive ones replace the // old one with a fresh promise. if (firstRun) { firstRun = false; } else { deferredD2Init = _libUtils.Deferred.create(); } var modelRequests = getModelRequests(api, config.schemas); var userRequests = [api.get('me', { fields: ':all,organisationUnits[id],userGroups[id],userCredentials[:all,!user,userRoles[id]' }), api.get('me/authorization'), getUserSettings()]; var systemRequests = [api.get('system/info'), api.get('apps')]; return Promise.all([].concat(_toConsumableArray(modelRequests), userRequests, systemRequests, [d2.i18n.load()])).then(function (res) { var responses = { schemas: (0, _libUtils.pick)('schemas')(res[0]), attributes: (0, _libUtils.pick)('attributes')(res[1]), currentUser: res[2], authorities: res[3], userSettings: res[4], systemInfo: res[5], apps: res[6] }; responses.schemas // TODO: Remove this when the schemas endpoint is versioned or shows the correct urls for the requested version // The schemas endpoint is not versioned which will result into the modelDefinitions always using the // "default" endpoint, we therefore modify the endpoint url based on the given baseUrl. .map(function (schema) { schema.apiEndpoint = (0, _libUtils.updateAPIUrlWithBaseUrlVersionNumber)(schema.apiEndpoint, config.baseUrl); // eslint-disable-line no-param-reassign return schema; }).forEach(function (schema) { // Attributes that do not have values do not by default get returned with the data, // therefore we need to grab the attributes that are attached to this particular schema to be able to know about them var schemaAttributes = responses.attributes.filter(function (attributeDescriptor) { var attributeNameFilter = [schema.singular, 'Attribute'].join(''); return attributeDescriptor[attributeNameFilter] === true; }); if (!Object.prototype.hasOwnProperty.call(d2.models, schema.singular)) { d2.models.add(_modelModels2['default'].ModelDefinition.createFromSchema(schema, schemaAttributes)); } }); d2.currentUser = _currentUserCurrentUser2['default'].create(responses.currentUser, responses.authorities, d2.models, responses.userSettings); d2.system.setSystemInfo(responses.systemInfo); d2.system.setInstalledApps(responses.apps); deferredD2Init.resolve(d2); return deferredD2Init.promise; })['catch'](function (error) { logger.error('Unable to get schemas from the api', JSON.stringify(error), error); deferredD2Init.reject('Unable to get schemas from the DHIS2 API'); return deferredD2Init.promise; }); } /** * @function getInstance * * @returns {Promise} A promise to an initialized d2 instance. * * @description * This function can be used to retrieve the `singleton` instance of d2. The instance is being created by calling * the `init` method. * * ```js * import {init, getInstance} from 'd2'; * * init({baseUrl: '/dhis2/api/'}); * getInstance() * .then(d2 => { * d2.models.dataElement.list(); * // and all your other d2 magic. * }); * ``` */ function getInstance() { return deferredD2Init.promise; } // Alias preInitConfig to be able to `import {config} from 'd2';` /** * @property config * * @description * Can be used to set config options before initialisation of d2. * * ```js * import {config, init} from 'd2'; * * config.baseUrl = '/demo/api'; * config.i18n.sources.add('i18n/systemsettingstranslations.properties'); * * init() * .then(d2 => { * d2.system.settings.all() * .then(systemSettings => Object.keys()) * .then(systemSettingsKey => { * d2.i18n.getTranslation(systemSettingsKey); * }); * }); * * ``` */ var config = preInitConfig; exports.config = config; exports['default'] = { init: init, config: config, getInstance: getInstance, getUserSettings: getUserSettings, getManifest: getManifest }; //# sourceMappingURL=d2.js.map