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'
7 type RawFunction<U, T> = (params: U) => T
8 type ObservableFunction<U, T> = RawFunction<U, Observable<T>>
11 export class HooksService {
12 constructor (private pluginService: PluginService) { }
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))
19 mergeMap(() => this.wrapObjectWithoutScopeLoad(params, hookParamName)),
20 switchMap(params => fun(params)),
21 mergeMap(result => this.pluginService.runHook(hookResultName, result, params))
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)
30 const newParams = await this.wrapObjectWithoutScopeLoad(params, hookParamName)
31 const result = fun(newParams)
33 return this.pluginService.runHook(hookResultName, result, params)
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 }))
42 async wrapObject<T, U extends ClientFilterHookName> (result: T, scope: PluginClientScope, hookName: U) {
43 await this.pluginService.ensurePluginsAreLoaded(scope)
45 return this.wrapObjectWithoutScopeLoad(result, hookName)
48 private wrapObjectWithoutScopeLoad<T, U extends ClientFilterHookName> (result: T, hookName: U) {
49 return this.pluginService.runHook(hookName, result)