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