aboutsummaryrefslogtreecommitdiffstats
path: root/packages/shared/plugins.ts
blob: 2ce5826adc86b2ea7892b0c9bf59e700dad318b3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Implementation inspired from Outline

import logger from "./logger";
import { SearchIndexClient } from "./search";

export enum PluginType {
  Search = "search",
}

interface PluginTypeMap {
  [PluginType.Search]: SearchIndexClient;
}

export interface TPlugin<T extends PluginType> {
  type: T;
  name: string;
  provider: PluginProvider<PluginTypeMap[T]>;
}

export interface PluginProvider<T> {
  getClient(): Promise<T | null>;
}

export class PluginManager {
  private static providers = new Map<PluginType, TPlugin<PluginType>[]>();

  static register<T extends PluginType>(plugin: TPlugin<T>): void {
    const p = PluginManager.providers.get(plugin.type);
    if (!p) {
      PluginManager.providers.set(plugin.type, [plugin]);
      return;
    }
    p.push(plugin);
  }

  static async getClient<T extends PluginType>(
    type: T,
  ): Promise<PluginTypeMap[T] | null> {
    const provider = PluginManager.providers.get(type);
    if (!provider) {
      return null;
    }
    return await provider[provider.length - 1].provider.getClient();
  }

  static isRegistered<T extends PluginType>(type: T): boolean {
    return !!PluginManager.providers.get(type);
  }

  static logAllPlugins() {
    logger.info("Plugins (Last one wins):");
    for (const type of Object.values(PluginType)) {
      logger.info(`  ${type}:`);
      const plugins = PluginManager.providers.get(type);
      if (!plugins) {
        logger.info("    - None");
        continue;
      }
      for (const plugin of plugins) {
        logger.info(`    - ${plugin.name}`);
      }
    }
  }
}