UNPKG

@communityox/ox_lib

Version:

JS/TS wrapper for ox_lib exports

42 lines (41 loc) 1.55 kB
import { cache } from '../cache'; const pendingCallbacks = {}; const callbackTimeout = GetConvarInt('ox:callbackTimeout', 300000); onNet(`__ox_cb_${cache.resource}`, (key, ...args) => { const resolve = pendingCallbacks[key]; if (!resolve) return; delete pendingCallbacks[key]; resolve(...args); }); export function triggerClientCallback(eventName, playerId, ...args) { let key; do { key = `${eventName}:${Math.floor(Math.random() * (100000 + 1))}:${playerId}`; } while (pendingCallbacks[key]); emitNet(`ox_lib:validateCallback`, playerId, eventName, cache.resource, key); emitNet(`__ox_cb_${eventName}`, playerId, cache.resource, key, ...args); return new Promise((resolve, reject) => { pendingCallbacks[key] = (args) => { if (args[0] === 'cb_invalid') reject(`callback '${eventName} does not exist`); resolve(args); }; setTimeout(reject, callbackTimeout, `callback event '${key}' timed out`); }); } export function onClientCallback(eventName, cb) { exports.ox_lib.setValidCallback(eventName, true); onNet(`__ox_cb_${eventName}`, async (resource, key, ...args) => { const src = source; let response; try { response = await cb(src, ...args); } catch (e) { console.error(`an error occurred while handling callback event ${eventName}`); console.log(`^3${e.stack}^0`); } emitNet(`__ox_cb_${resource}`, src, key, response); }); }