property-provider.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 { ModelServerConfig as Config } from './config';
  9. import { ConsoleLogger } from '../../mol-util/console-logger';
  10. // TODO enable dynamic imports again
  11. import * as pdbeProps from './properties/pdbe';
  12. import * as wwpdbProps from './properties/wwpdb';
  13. const attachModelProperties: { [k: string]: AttachModelProperties } = {
  14. pdbe: pdbeProps.attachModelProperties,
  15. wwpdb: wwpdbProps.attachModelProperties
  16. };
  17. export interface ModelPropertyProviderConfig {
  18. sources: string[],
  19. params?: { [name: string]: any }
  20. }
  21. export type AttachModelProperty = (args: { model: Model, params: any, cache: any }) => Promise<any>
  22. export type AttachModelProperties = (args: { model: Model, params: any, cache: any }) => Promise<any>[]
  23. export type ModelPropertiesProvider = (model: Model, cache: any) => Promise<any>[]
  24. export function createModelPropertiesProviderFromConfig() {
  25. return createModelPropertiesProvider(Config.customProperties);
  26. }
  27. export function createModelPropertiesProvider(configOrPath: ModelPropertyProviderConfig | string | undefined): ModelPropertiesProvider | undefined {
  28. let config: ModelPropertyProviderConfig;
  29. if (typeof configOrPath === 'string') {
  30. try {
  31. config = JSON.parse(fs.readFileSync(configOrPath, 'utf8'));
  32. } catch {
  33. ConsoleLogger.error('Config', `Could not read property provider config file '${configOrPath}', ignoring.`);
  34. return () => [];
  35. }
  36. } else {
  37. config = configOrPath!;
  38. }
  39. if (!config || !config.sources || config.sources.length === 0) return void 0;
  40. const ps: AttachModelProperties[] = [];
  41. for (const p of config.sources) {
  42. if (p in attachModelProperties) {
  43. ps.push(attachModelProperties[p]);
  44. } else {
  45. ConsoleLogger.error('Config', `Could not find property provider '${p}', ignoring.`);
  46. }
  47. }
  48. return (model, cache) => {
  49. const ret: Promise<any>[] = [];
  50. for (const p of ps) {
  51. for (const e of p({ model, cache, params: config.params })) ret.push(e);
  52. }
  53. return ret;
  54. };
  55. }