Files
ox_lib/package/server/resource/callback/index.ts

43 lines
1.2 KiB
TypeScript
Raw Normal View History

2022-12-11 12:40:19 +11:00
import { cache } from '../cache';
2023-09-16 10:37:14 +02:00
const activeEvents: Record<string, (...args: any[]) => void> = {};
2022-12-11 12:40:19 +11:00
onNet(`__ox_cb_${cache.resource}`, (key: string, ...args: any) => {
const resolve = activeEvents[key];
return resolve && resolve(...args);
});
export function triggerClientCallback<T = unknown>(
eventName: string,
playerId: number,
...args: any
): Promise<T> | void {
2022-12-11 12:40:19 +11:00
let key: string;
do {
key = `${eventName}:${Math.floor(Math.random() * (100000 + 1))}:${playerId}`;
} while (activeEvents[key]);
emitNet(`__ox_cb_${eventName}`, playerId, cache.resource, key, ...args);
return new Promise<T>((resolve) => {
2022-12-11 12:40:19 +11:00
activeEvents[key] = resolve;
});
}
2023-09-16 10:37:14 +02:00
export function onClientCallback(eventName: string, cb: (playerId: number, ...args: any[]) => any) {
onNet(`__ox_cb_${eventName}`, async (resource: string, key: string, ...args: any[]) => {
2022-12-11 12:40:19 +11:00
const src = source;
let response: any;
try {
response = await cb(src, ...args);
2022-12-11 12:40:19 +11:00
} catch (e: any) {
console.error(`an error occurred while handling callback event ${eventName}`);
console.log(`^3${e.stack}^0`);
}
emitNet(`__ox_cb_${resource}`, src, key, response);
});
}