mirror of
https://github.com/CommunityOx/ox_lib.git
synced 2026-08-17 06:56:03 +01:00
feat(package): TS callback events
This commit is contained in:
38
package/server/resource/callback/index.ts
Normal file
38
package/server/resource/callback/index.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { cache } from '../cache';
|
||||
|
||||
const activeEvents: Record<string, Function> = {};
|
||||
|
||||
onNet(`__ox_cb_${cache.resource}`, (key: string, ...args: any) => {
|
||||
const resolve = activeEvents[key];
|
||||
return resolve && resolve(...args);
|
||||
});
|
||||
|
||||
export function triggerClientCallback(eventName: string, playerId: number, ...args: any) {
|
||||
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((resolve) => {
|
||||
activeEvents[key] = resolve;
|
||||
});
|
||||
}
|
||||
|
||||
export function onClientCallback(eventName: string, cb: (playerId: number, ...args: any) => any) {
|
||||
onNet(`__ox_cb_${eventName}`, (resource: string, key: string, ...args: any) => {
|
||||
const src = source;
|
||||
let response: any;
|
||||
|
||||
try {
|
||||
response = cb(src, ...args);
|
||||
} 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);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user