loader.ts 2.6 KB

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