Source: data/sources.js

  1. import {RegistryBase} from '../registry/base';
  2. import { ADAPTERS } from '../registry';
  3. /**
  4. * Create and coordinate an ensemble of (namespaced) data adapter instances.
  5. * This is the mechanism by which users tell a plot how to retrieve data for a specific plot: adapters are created
  6. * through this object rather than instantiating directly.
  7. *
  8. * @public
  9. * @alias module:LocusZoom~DataSources
  10. * @extends module:registry/base~RegistryBase
  11. * @inheritDoc
  12. */
  13. class DataSources extends RegistryBase {
  14. /**
  15. * @param {RegistryBase} [registry] Primarily used for unit testing. When creating sources by name, specify where to
  16. * find the registry of known sources.
  17. */
  18. constructor(registry) {
  19. super();
  20. // This both acts as a registry (of the instantiated sources for this plot), and references a registry
  21. // (to locate adapter classes by name, when creating from config)
  22. this._registry = registry || ADAPTERS;
  23. }
  24. /**
  25. * For data sources, there is a special behavior of "create item from config, then add"
  26. * @param {String} namespace Uniquely identify this datasource
  27. * @param {BaseAdapter|Array} item An instantiated datasource, or an array of arguments that can be used to
  28. * create a known datasource type.
  29. * @param [override=false] Whether to allow existing sources to be redefined
  30. * @return {DataSources} Most registries return the created instance, but this registry returns a reference to
  31. * itself (to support chaining)
  32. */
  33. add(namespace, item, override = false) {
  34. if (this._registry.has(namespace)) {
  35. throw new Error(`The namespace ${namespace} is already in use by another source`);
  36. }
  37. if (namespace.match(/[^A-Za-z0-9_]/)) {
  38. throw new Error(`Data source namespace names can only contain alphanumeric characters or underscores. Invalid name: ${namespace}`);
  39. }
  40. if (Array.isArray(item)) {
  41. const [type, options] = item;
  42. item = this._registry.create(type, options);
  43. }
  44. // Each datasource in the chain should be aware of its assigned namespace
  45. item.source_id = namespace;
  46. super.add(namespace, item, override);
  47. return this;
  48. }
  49. }
  50. export default DataSources;