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'
9 type RawFunction<U, T> = (params: U) => T
10 type ObservableFunction<U, T> = RawFunction<U, Observable<T>>
13 export class HooksService {
15 private server: ServerService,
16 private pluginService: PluginService
20 <P, R, H1 extends ClientFilterHookName, H2 extends ClientFilterHookName>
21 (fun: ObservableFunction<P, R>, params: P, scope: PluginClientScope, hookParamName: H1, hookResultName: H2)
23 return from(this.pluginService.ensurePluginsAreLoaded(scope))
25 mergeMap(() => this.wrapObject(params, hookParamName)),
26 switchMap(params => fun(params)),
27 mergeMap(result => this.pluginService.runHook(hookResultName, result, params))
32 <P, R, H1 extends ClientFilterHookName, H2 extends ClientFilterHookName>
33 (fun: RawFunction<P, R>, params: P, scope: PluginClientScope, hookParamName: H1, hookResultName: H2)
35 await this.pluginService.ensurePluginsAreLoaded(scope)
37 const newParams = await this.wrapObject(params, hookParamName)
38 const result = fun(newParams)
40 return this.pluginService.runHook(hookResultName, result, params)
43 runAction<T, U extends ClientActionHookName> (hookName: U, scope: PluginClientScope, params?: T) {
44 this.pluginService.ensurePluginsAreLoaded(scope)
45 .then(() => this.pluginService.runHook(hookName, undefined, params))
46 .catch((err: any) => console.error('Fatal hook error.', { err }))
49 private wrapObject<T, U extends ClientFilterHookName> (result: T, hookName: U) {
50 return this.pluginService.runHook(hookName, result)