loader.ts 2.7 KB

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