wangzhibo
2026-07-16 bac4362a0b7726d38a23d38f0d7913f2c2bab262
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import {
  App,
  IMidwayApplication,
  Inject,
  InjectClient,
  Scope,
  Provide,
  ScopeEnum,
} from '@midwayjs/core';
import * as fs from 'fs';
import * as path from 'path';
import { PluginInfoEntity } from '../entity/info';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { PluginInfo } from '../interface';
import * as _ from 'lodash';
import { CachingFactory, MidwayCache } from '@midwayjs/cache-manager';
import { CoolEventManager } from '@cool-midway/core';
import { PluginService } from './info';
 
export const PLUGIN_CACHE_KEY = 'plugin:init';
 
export const EVENT_PLUGIN_READY = 'EVENT_PLUGIN_READY';
 
/**
 * 插件中心
 */
@Provide()
@Scope(ScopeEnum.Singleton)
export class PluginCenterService {
  // 插件列表
  plugins: Map<string, any> = new Map();
 
  // 插件配置
  pluginInfos: Map<string, PluginInfo> = new Map();
 
  @App()
  app: IMidwayApplication;
 
  @InjectEntityModel(PluginInfoEntity)
  pluginInfoEntity: Repository<PluginInfoEntity>;
 
  @InjectClient(CachingFactory, 'default')
  midwayCache: MidwayCache;
 
  @Inject()
  coolEventManager: CoolEventManager;
 
  @Inject()
  pluginService: PluginService;
 
  /**
   * 初始化
   * @returns
   */
  async init() {
    this.plugins.clear();
    await this.initHooks();
    await this.initPlugin();
    this.coolEventManager.emit(EVENT_PLUGIN_READY);
  }
 
  /**
   * 初始化一个
   * @param keyName key名
   */
  async initOne(keyName: string) {
    await this.initPlugin({
      keyName,
    });
    this.coolEventManager.emit(EVENT_PLUGIN_READY, keyName);
  }
 
  /**
   * 移除插件
   * @param keyName
   * @param isHook
   */
  async remove(keyName: string, isHook = false) {
    this.plugins.delete(keyName);
    this.pluginInfos.delete(keyName);
    if (isHook) {
      await this.initHooks();
    }
  }
 
  /**
   * 注册插件
   * @param key 唯一标识
   * @param cls 类
   * @param pluginInfo 插件信息
   */
  async register(key: string, cls: any, pluginInfo?: PluginInfo) {
    // 单例插件
    if (pluginInfo?.singleton) {
      const instance = new cls();
      await instance.init(this.pluginInfos.get(key), null, this.app, {
        cache: this.midwayCache,
        pluginService: this.pluginService,
      });
      this.plugins.set(key, instance);
    } else {
      // 普通插件
      this.plugins.set(key, cls);
    }
  }
 
  /**
   * 初始化钩子
   */
  async initHooks() {
    const hooksPath = path.join(
      this.app.getBaseDir(),
      'modules',
      'plugin',
      'hooks'
    );
    for (const key of fs.readdirSync(hooksPath)) {
      const stat = fs.statSync(path.join(hooksPath, key));
      if (!stat.isDirectory()) {
        continue;
      }
      const { Plugin } = await import(path.join(hooksPath, key, 'index'));
      await this.register(key, Plugin);
      this.pluginInfos.set(key, {
        name: key,
        config: this.app.getConfig('module.plugin.hooks.' + key),
      });
    }
  }
 
  /**
   * 初始化插件
   * @param condition 插件条件
   */
  async initPlugin(condition?: {
    hook?: string;
    id?: number;
    keyName?: string;
  }) {
    let find: any = { status: 1 };
    if (condition) {
      find = {
        ...find,
        ...condition,
      };
    }
    const plugins = await this.pluginInfoEntity.find({
      where: find,
      select: [
        'id',
        'name',
        'description',
        'keyName',
        'hook',
        'version',
        'pluginJson',
        'config',
      ],
    });
    for (const plugin of plugins) {
      const data = await this.pluginService.getData(plugin.keyName);
      if (!data) {
        continue;
      }
      const instance = await this.getInstance(data.content.data);
      const pluginInfo = {
        ...plugin.pluginJson,
        config: this.getConfig(plugin.config),
      };
      if (plugin.hook) {
        this.pluginInfos.set(plugin.hook, pluginInfo);
        await this.register(plugin.hook, instance, pluginInfo);
      } else {
        this.pluginInfos.set(plugin.keyName, pluginInfo);
        await this.register(plugin.keyName, instance, pluginInfo);
      }
    }
  }
 
  /**
   * 获得配置
   * @param config
   * @returns
   */
  private getConfig(config: any) {
    // 处理配置为字符串的情况
    if (typeof config === 'string') {
      try {
        config = JSON.parse(config);
      } catch (e) {
        return {};
      }
    }
    // 如果配置为空或非对象类型,则返回空对象
    if (!config || typeof config !== 'object') {
      return {};
    }
    const env = this.app.getEnv();
    let isMulti = false;
    for (const key in config) {
      if (key.includes('@')) {
        isMulti = true;
        break;
      }
    }
    return isMulti ? config[`@${env}`] : config;
  }
 
  /**
   * 获得实例
   * @param content
   * @returns
   */
  async getInstance(content: string) {
    let _instance;
    const script = `
        ${content} 
        _instance = Plugin;
    `;
    eval(script);
    return _instance;
  }
}