diff --git a/.changeset/polite-cows-run.md b/.changeset/polite-cows-run.md new file mode 100644 index 00000000..eb85941b --- /dev/null +++ b/.changeset/polite-cows-run.md @@ -0,0 +1,5 @@ +--- +'pockethost': minor +--- + +Added support for priorities in actions diff --git a/packages/pockethost/src/common/plugin/action.ts b/packages/pockethost/src/common/plugin/action.ts index e69756e7..ebe6a8da 100644 --- a/packages/pockethost/src/common/plugin/action.ts +++ b/packages/pockethost/src/common/plugin/action.ts @@ -1,4 +1,6 @@ +import { uniqueId } from '@s-libs/micro-dash' import { Express, Request, Response } from 'express' +import { dbg } from '../../cli' import { LogLevelName } from '../Logger' import { DEBUG } from '../debug' import { InstanceFields } from '../schema' @@ -28,20 +30,34 @@ enum CoreActions { Request = 'core_edge_request', } -const actions: { - [key: string]: ActionHandler[] -} = {} - export type ActionHandler = ( context: TContext extends never ? [] : TContext, ) => Promise -async function registerAction( +interface Action { + priority: number + handler: ActionHandler +} + +const actions: { + [key: string]: Action[] +} = {} + +function registerAction( action: string, handler: (...args: any[]) => Promise, -) { + priority: number = 10, +): () => void { if (!(action in actions)) actions[action] = [] - actions[action]!.push(handler) + const uid = uniqueId(`a:${action}:`) + dbg(`${uid}:subscribe`) + actions[action]!.push({ priority, handler }) + actions[action]!.sort((a, b) => a.priority - b.priority) + + return () => { + dbg(`${uid}:unsubscribe`) + actions[action] = actions[action]!.filter((a) => a.handler !== handler) + } } async function action(actionName: string, context: any) { @@ -59,15 +75,16 @@ export function createCustomActionWithContext( ) { return [ async (context: TContext) => action(actionName, context), - async (handler: ActionHandler) => - registerAction(actionName, handler), + (handler: ActionHandler, priority = 10) => + registerAction(actionName, handler, priority), ] as const } export function createCustomAction(actionName: CoreActions) { return [ async () => action(actionName, {}), - async (handler: ActionHandler) => registerAction(actionName, handler), + (handler: ActionHandler, priority = 10) => + registerAction(actionName, handler, priority), ] as const }