loader.ts 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { mapperManager } from './mappers';
  2. import { ViewerConfiguration } from './configuration';
  3. import { getConfigurationType } from './types';
  4. import * as deepmerge from '../../assets/deepmerge.min.js';
  5. export class ConfigurationLoader {
  6. private configurationCache: { [url: string]: any };
  7. constructor() {
  8. this.configurationCache = {};
  9. }
  10. public loadConfiguration(initConfig: ViewerConfiguration = {}): Promise<ViewerConfiguration> {
  11. let loadedConfig = deepmerge({}, initConfig);
  12. let extendedConfiguration = getConfigurationType(loadedConfig && loadedConfig.extends);
  13. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  14. if (loadedConfig.configuration) {
  15. let mapperType = "json";
  16. return Promise.resolve().then(() => {
  17. if (typeof loadedConfig.configuration === "string" || loadedConfig.configuration.url) {
  18. // a file to load
  19. let url = loadedConfig.configuration;
  20. // if configuration is an object
  21. if (loadedConfig.configuration.url) {
  22. url = loadedConfig.configuration.url;
  23. mapperType = loadedConfig.configuration.mapper;
  24. if (!mapperType) {
  25. // load mapper type from filename / url
  26. mapperType = loadedConfig.configuration.url.split('.').pop();
  27. }
  28. }
  29. return this.loadFile(url);
  30. } else {
  31. mapperType = loadedConfig.configuration.mapper || mapperType;
  32. return loadedConfig.configuration.payload || {};
  33. }
  34. }).then((data: any) => {
  35. let mapper = mapperManager.getMapper(mapperType);
  36. let parsed = mapper.map(data);
  37. return deepmerge(loadedConfig, parsed);
  38. });
  39. } else {
  40. return Promise.resolve(loadedConfig);
  41. }
  42. }
  43. public getConfigurationType(type: string) {
  44. }
  45. private loadFile(url: string): Promise<any> {
  46. let cacheReference = this.configurationCache;
  47. if (cacheReference[url]) {
  48. return Promise.resolve(cacheReference[url]);
  49. }
  50. return new Promise(function (resolve, reject) {
  51. var xhr = new XMLHttpRequest();
  52. xhr.open('GET', url);
  53. xhr.send();
  54. xhr.onreadystatechange = function () {
  55. var DONE = 4;
  56. var OK = 200;
  57. if (xhr.readyState === DONE) {
  58. if (xhr.status === OK) {
  59. cacheReference[url] = xhr.responseText;
  60. resolve(xhr.responseText); // 'This is the returned text.'
  61. } else {
  62. console.log('Error: ' + xhr.status, url);
  63. reject('Error: ' + xhr.status); // An error occurred during the request.
  64. }
  65. }
  66. }
  67. });
  68. }
  69. }
  70. export let configurationLoader = new ConfigurationLoader();
  71. export default configurationLoader;