1 | const fs = require('fs-extra');
|
2 | const path = require('path');
|
3 |
|
4 | let plugins = [];
|
5 |
|
6 | function mapOrder(array, order, key) {
|
7 | array.sort((a, b) => {
|
8 | let A = a[key], B = b[key];
|
9 |
|
10 | if (!order.includes(A)) return 1;
|
11 | if (!order.includes(B)) return -1;
|
12 |
|
13 | return order.indexOf(A) > order.indexOf(B);
|
14 | });
|
15 |
|
16 | return array;
|
17 | }
|
18 |
|
19 | module.exports = class plugin {
|
20 | static async compile(installDir) {
|
21 | let config = await fs.readJson(path.join(process.env.BLAZE_INSTANCE, 'config.json'));
|
22 | let files = (await fs.readdir(path.join(installDir, 'plugins'))).filter(fileName => fileName.endsWith('.js'));
|
23 |
|
24 | let compiledPlugins = [];
|
25 |
|
26 | for (let fileIndex = 0; fileIndex < files.length; fileIndex++) {
|
27 | const fileName = files[fileIndex];
|
28 | try {
|
29 | compiledPlugins.push({
|
30 | "id": fileName.replace('.js', ''),
|
31 | "name": fileName,
|
32 | "module": require(path.join(installDir, 'plugins', fileName))
|
33 | });
|
34 | } catch (error) {
|
35 | throw ('Failed to load plugin ' + fileName);
|
36 | }
|
37 | }
|
38 | plugins = mapOrder(compiledPlugins, config.plugins, 'id');
|
39 | }
|
40 |
|
41 | static async fire($_CONTEXT, event) {
|
42 | for (let pluginIndex = 0; pluginIndex < plugins.length; pluginIndex++) {
|
43 | const plugin = plugins[pluginIndex];
|
44 | if (plugin.module.hasOwnProperty(event)) {
|
45 | if ('function' === typeof plugin.module[event]) {
|
46 | await plugin.module[event]($_CONTEXT);
|
47 | }
|
48 | }
|
49 | }
|
50 | }
|
51 |
|
52 | static get BEFORE_REQUEST() {
|
53 | return 'beforeRequest';
|
54 | }
|
55 |
|
56 | static get AFTER_REQUEST() {
|
57 | return 'afterRequest';
|
58 | }
|
59 |
|
60 | static get BEFORE_TIMEOUT() {
|
61 | return 'beforeTimeout';
|
62 | }
|
63 |
|
64 | static get AFTER_TIMEOUT() {
|
65 | return 'afterTimeout';
|
66 | }
|
67 |
|
68 | static get BEFORE_ERROR() {
|
69 | return 'beforeError';
|
70 | }
|
71 |
|
72 | static get AFTER_ERROR() {
|
73 | return 'afterError';
|
74 | }
|
75 | } |
\ | No newline at end of file |