property-provider.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import * as fs from 'fs'
  7. import { Model } from 'mol-model/structure';
  8. import Config from './config';
  9. import { ConsoleLogger } from 'mol-util/console-logger';
  10. export interface ModelPropertyProviderConfig {
  11. sources: string[],
  12. params?: { [name: string]: any }
  13. }
  14. export type AttachModelProperty = (args: { model: Model, params: any, cache: any }) => Promise<any>
  15. export type AttachModelProperties = (args: { model: Model, params: any, cache: any }) => Promise<any>[]
  16. export type ModelPropertiesProvider = (model: Model, cache: any) => Promise<any>[]
  17. export function createModelPropertiesProviderFromConfig() {
  18. return createModelPropertiesProvider(Config.customProperties);
  19. }
  20. export function createModelPropertiesProvider(configOrPath: ModelPropertyProviderConfig | string | undefined): ModelPropertiesProvider | undefined {
  21. let config: ModelPropertyProviderConfig;
  22. if (typeof configOrPath === 'string') {
  23. try {
  24. config = JSON.parse(fs.readFileSync(configOrPath, 'utf8'));
  25. } catch {
  26. ConsoleLogger.error('Config', `Could not read property provider config file '${configOrPath}', ignoring.`);
  27. return () => [];
  28. }
  29. } else {
  30. config = configOrPath!;
  31. }
  32. if (!config || !config.sources || config.sources.length === 0) return void 0;
  33. const ps: AttachModelProperties[] = [];
  34. for (const p of config.sources) {
  35. ps.push(require(p).attachModelProperties);
  36. }
  37. return (model, cache) => {
  38. const ret: Promise<any>[] = [];
  39. for (const p of ps) {
  40. for (const e of p({ model, cache, params: config.params })) ret.push(e);
  41. }
  42. return ret;
  43. }
  44. }