]>
Commit | Line | Data |
---|---|---|
93cae479 C |
1 | import { Injectable } from '@angular/core' |
2 | import { PluginService } from '@app/core/plugins/plugin.service' | |
3 | import { ClientActionHookName, ClientFilterHookName } from '@shared/models/plugins/client-hook.model' | |
4 | import { from, Observable } from 'rxjs' | |
5 | import { mergeMap, switchMap } from 'rxjs/operators' | |
6 | import { ServerService } from '@app/core/server' | |
7 | import { PluginClientScope } from '@shared/models/plugins/plugin-client-scope.type' | |
8 | ||
9 | type RawFunction<U, T> = (params: U) => T | |
10 | type ObservableFunction<U, T> = RawFunction<U, Observable<T>> | |
11 | ||
12 | @Injectable() | |
13 | export class HooksService { | |
14 | constructor ( | |
15 | private server: ServerService, | |
16 | private pluginService: PluginService | |
17 | ) { } | |
18 | ||
93cae479 C |
19 | wrapObsFun |
20 | <P, R, H1 extends ClientFilterHookName, H2 extends ClientFilterHookName> | |
0912f1b4 | 21 | (fun: ObservableFunction<P, R>, params: P, scope: PluginClientScope, hookParamName: H1, hookResultName: H2) { |
93cae479 C |
22 | return from(this.pluginService.ensurePluginsAreLoaded(scope)) |
23 | .pipe( | |
0912f1b4 | 24 | mergeMap(() => this.wrapObjectWithoutScopeLoad(params, hookParamName)), |
93cae479 C |
25 | switchMap(params => fun(params)), |
26 | mergeMap(result => this.pluginService.runHook(hookResultName, result, params)) | |
27 | ) | |
28 | } | |
29 | ||
c2023a9f C |
30 | async wrapFun |
31 | <P, R, H1 extends ClientFilterHookName, H2 extends ClientFilterHookName> | |
0912f1b4 | 32 | (fun: RawFunction<P, R>, params: P, scope: PluginClientScope, hookParamName: H1, hookResultName: H2) { |
c2023a9f C |
33 | await this.pluginService.ensurePluginsAreLoaded(scope) |
34 | ||
0912f1b4 | 35 | const newParams = await this.wrapObjectWithoutScopeLoad(params, hookParamName) |
c2023a9f | 36 | const result = fun(newParams) |
93cae479 | 37 | |
c2023a9f | 38 | return this.pluginService.runHook(hookResultName, result, params) |
93cae479 C |
39 | } |
40 | ||
c9e3eeed C |
41 | runAction<T, U extends ClientActionHookName> (hookName: U, scope: PluginClientScope, params?: T) { |
42 | this.pluginService.ensurePluginsAreLoaded(scope) | |
23bdacf8 | 43 | .then(() => this.pluginService.runHook(hookName, undefined, params)) |
c9e3eeed | 44 | .catch((err: any) => console.error('Fatal hook error.', { err })) |
93cae479 | 45 | } |
c2023a9f | 46 | |
0912f1b4 C |
47 | async wrapObject<T, U extends ClientFilterHookName> (result: T, scope: PluginClientScope, hookName: U) { |
48 | await this.pluginService.ensurePluginsAreLoaded(scope) | |
49 | ||
50 | return this.wrapObjectWithoutScopeLoad(result, hookName) | |
51 | } | |
52 | ||
53 | private wrapObjectWithoutScopeLoad<T, U extends ClientFilterHookName> (result: T, hookName: U) { | |
c2023a9f C |
54 | return this.pluginService.runHook(hookName, result) |
55 | } | |
93cae479 | 56 | } |