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 } from '@shared/models/plugins/client-hook.model'
6 import { PluginClientScope } from '@shared/models/plugins/plugin-client-scope.type'
8 type RawFunction<U, T> = (params: U) => T
9 type ObservableFunction<U, T> = RawFunction<U, Observable<T>>
12 export class HooksService {
13 constructor (private pluginService: PluginService) { }
16 <P, R, H1 extends ClientFilterHookName, H2 extends ClientFilterHookName>
17 (fun: ObservableFunction<P, R>, params: P, scope: PluginClientScope, hookParamName: H1, hookResultName: H2) {
18 return from(this.pluginService.ensurePluginsAreLoaded(scope))
20 mergeMap(() => this.wrapObjectWithoutScopeLoad(params, hookParamName)),
21 switchMap(params => fun(params)),
22 mergeMap(result => this.pluginService.runHook(hookResultName, result, params))
27 <P, R, H1 extends ClientFilterHookName, H2 extends ClientFilterHookName>
28 (fun: RawFunction<P, R>, params: P, scope: PluginClientScope, hookParamName: H1, hookResultName: H2) {
29 await this.pluginService.ensurePluginsAreLoaded(scope)
31 const newParams = await this.wrapObjectWithoutScopeLoad(params, hookParamName)
32 const result = fun(newParams)
34 return this.pluginService.runHook(hookResultName, result, params)
37 runAction<T, U extends ClientActionHookName> (hookName: U, scope: PluginClientScope, params?: T) {
38 this.pluginService.ensurePluginsAreLoaded(scope)
39 .then(() => this.pluginService.runHook(hookName, undefined, params))
40 .catch((err: any) => console.error('Fatal hook error.', { err }))
43 async wrapObject<T, U extends ClientFilterHookName> (result: T, scope: PluginClientScope, hookName: U) {
44 await this.pluginService.ensurePluginsAreLoaded(scope)
46 return this.wrapObjectWithoutScopeLoad(result, hookName)
49 private wrapObjectWithoutScopeLoad<T, U extends ClientFilterHookName> (result: T, hookName: U) {
50 return this.pluginService.runHook(hookName, result)