]>
Commit | Line | Data |
---|---|---|
1 | import { from, Observable } from 'rxjs' | |
2 | import { mergeMap, switchMap } from 'rxjs/operators' | |
3 | import { Injectable } from '@angular/core' | |
4 | import { PluginService } from '@app/core/plugins/plugin.service' | |
5 | import { ClientActionHookName, ClientFilterHookName, PluginClientScope } from '@shared/models' | |
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 { | |
12 | constructor (private pluginService: PluginService) { } | |
13 | ||
14 | wrapObsFun | |
15 | <P, R, H1 extends ClientFilterHookName, H2 extends ClientFilterHookName> | |
16 | (fun: ObservableFunction<P, R>, params: P, scope: PluginClientScope, hookParamName: H1, hookResultName: H2) { | |
17 | return from(this.pluginService.ensurePluginsAreLoaded(scope)) | |
18 | .pipe( | |
19 | mergeMap(() => this.wrapObjectWithoutScopeLoad(params, hookParamName)), | |
20 | switchMap(params => fun(params)), | |
21 | mergeMap(result => this.pluginService.runHook(hookResultName, result, params)) | |
22 | ) | |
23 | } | |
24 | ||
25 | async wrapFun | |
26 | <P, R, H1 extends ClientFilterHookName, H2 extends ClientFilterHookName> | |
27 | (fun: RawFunction<P, R>, params: P, scope: PluginClientScope, hookParamName: H1, hookResultName: H2) { | |
28 | await this.pluginService.ensurePluginsAreLoaded(scope) | |
29 | ||
30 | const newParams = await this.wrapObjectWithoutScopeLoad(params, hookParamName) | |
31 | const result = fun(newParams) | |
32 | ||
33 | return this.pluginService.runHook(hookResultName, result, params) | |
34 | } | |
35 | ||
36 | runAction<T, U extends ClientActionHookName> (hookName: U, scope: PluginClientScope, params?: T) { | |
37 | this.pluginService.ensurePluginsAreLoaded(scope) | |
38 | .then(() => this.pluginService.runHook(hookName, undefined, params)) | |
39 | .catch((err: any) => console.error('Fatal hook error.', { err })) | |
40 | } | |
41 | ||
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) { | |
49 | return this.pluginService.runHook(hookName, result) | |
50 | } | |
51 | } |