feat(pockethost): action priorities

This commit is contained in:
Ben Allfree 2024-06-29 14:20:16 -07:00
parent cce72b35e2
commit c473ed9da4
2 changed files with 32 additions and 10 deletions

View File

@ -0,0 +1,5 @@
---
'pockethost': minor
---
Added support for priorities in actions

View File

@ -1,4 +1,6 @@
import { uniqueId } from '@s-libs/micro-dash'
import { Express, Request, Response } from 'express' import { Express, Request, Response } from 'express'
import { dbg } from '../../cli'
import { LogLevelName } from '../Logger' import { LogLevelName } from '../Logger'
import { DEBUG } from '../debug' import { DEBUG } from '../debug'
import { InstanceFields } from '../schema' import { InstanceFields } from '../schema'
@ -28,20 +30,34 @@ enum CoreActions {
Request = 'core_edge_request', Request = 'core_edge_request',
} }
const actions: {
[key: string]: ActionHandler<any>[]
} = {}
export type ActionHandler<TContext = {}> = ( export type ActionHandler<TContext = {}> = (
context: TContext extends never ? [] : TContext, context: TContext extends never ? [] : TContext,
) => Promise<void> ) => Promise<void>
async function registerAction( interface Action {
priority: number
handler: ActionHandler<any>
}
const actions: {
[key: string]: Action[]
} = {}
function registerAction(
action: string, action: string,
handler: (...args: any[]) => Promise<void>, handler: (...args: any[]) => Promise<void>,
) { priority: number = 10,
): () => void {
if (!(action in actions)) actions[action] = [] 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) { async function action(actionName: string, context: any) {
@ -59,15 +75,16 @@ export function createCustomActionWithContext<TContext extends {}>(
) { ) {
return [ return [
async (context: TContext) => action(actionName, context), async (context: TContext) => action(actionName, context),
async (handler: ActionHandler<TContext>) => (handler: ActionHandler<TContext>, priority = 10) =>
registerAction(actionName, handler), registerAction(actionName, handler, priority),
] as const ] as const
} }
export function createCustomAction(actionName: CoreActions) { export function createCustomAction(actionName: CoreActions) {
return [ return [
async () => action(actionName, {}), async () => action(actionName, {}),
async (handler: ActionHandler) => registerAction(actionName, handler), (handler: ActionHandler, priority = 10) =>
registerAction(actionName, handler, priority),
] as const ] as const
} }