mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-19 23:33:13 +09:00
Strongly type invokeHook
Add strong typing of the invokeHook function to prevent incorrect paramaters being passed to plugin hooks. This detected a few places where the parameters passed were incorrect.
This commit is contained in:
1 parent
e3e5867d60
commit
654df76065
7 files changed
+24
-18
No files matched your search
@@ -3,6 +3,7 @@
|
||||
* @module lib/plugin
|
||||
*/
|
||||
import * as libHelpers from "./helpers";
|
||||
import type { Logger } from "./logging";
|
||||
import type { PluginConfigGroup } from "./config";
|
||||
import type PlayerStats from "./PlayerStats";
|
||||
|
||||
@@ -71,14 +72,22 @@ export interface PlayerEvent {
|
||||
* @param args - Arguments to pass on to the hook.
|
||||
* @returns Non-undefined return values from the hooks.
|
||||
*/
|
||||
export async function invokeHook(plugins: Map<string, any>, hook: string, ...args: any[]) {
|
||||
let results: unknown[] = [];
|
||||
export async function invokeHook<
|
||||
Hook extends string,
|
||||
R,
|
||||
Args extends [...any],
|
||||
Plugin extends { logger: Logger } & Record<Hook, (...hookArgs: Args) => R | Promise<R>>
|
||||
>(
|
||||
plugins: Map<string, Plugin>,
|
||||
hook: Hook,
|
||||
...args: Args
|
||||
): Promise<Exclude<Awaited<ReturnType<Plugin[Hook]>>, void>[]> {
|
||||
let results: any[] = [];
|
||||
for (let [name, plugin] of plugins) {
|
||||
try {
|
||||
// Use an object to detect if the hook failed on timeout or tried to return a value looking like an error
|
||||
const timeout = {};
|
||||
let result = await libHelpers.timeout(
|
||||
(plugin as any)[hook](...args),
|
||||
const timeout = Symbol("timeout-token");
|
||||
let result = await libHelpers.timeout<R | typeof timeout>(
|
||||
plugin[hook](...args) as Promise<R>,
|
||||
15000,
|
||||
timeout
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user