mirror of
https://github.com/CommunityOx/ox_lib.git
synced 2026-08-17 06:56:03 +01:00
feat(callback): implement callback validation
Prevent callbacks from being overwritten by other resources. Throw an immediate error if the callback does not exist.
This commit is contained in:
@@ -4,9 +4,12 @@ local callbackTimeout = GetConvarInt('ox:callbackTimeout', 300000)
|
||||
|
||||
RegisterNetEvent(cbEvent:format(cache.resource), function(key, ...)
|
||||
local cb = pendingCallbacks[key]
|
||||
|
||||
if not cb then return end
|
||||
|
||||
pendingCallbacks[key] = nil
|
||||
|
||||
return cb and cb(...)
|
||||
cb(...)
|
||||
end)
|
||||
|
||||
---@param _ any
|
||||
@@ -24,12 +27,19 @@ local function triggerClientCallback(_, event, playerId, cb, ...)
|
||||
key = ('%s:%s:%s'):format(event, math.random(0, 100000), playerId)
|
||||
until not pendingCallbacks[key]
|
||||
|
||||
TriggerClientEvent('ox_lib:validateCallback', playerId, event, cache.resource, key)
|
||||
TriggerClientEvent(cbEvent:format(event), playerId, cache.resource, key, ...)
|
||||
|
||||
---@type promise | false
|
||||
local promise = not cb and promise.new()
|
||||
|
||||
pendingCallbacks[key] = function(response, ...)
|
||||
if response == 'cb_invalid' then
|
||||
response = ("callback '%s' does not exist"):format(event)
|
||||
|
||||
return promise and promise:reject(response) or error(response)
|
||||
end
|
||||
|
||||
response = { response, ... }
|
||||
|
||||
if promise then
|
||||
@@ -96,7 +106,11 @@ local pcall = pcall
|
||||
---Registers an event handler and callback function to respond to client requests.
|
||||
---@diagnostic disable-next-line: duplicate-set-field
|
||||
function lib.callback.register(name, cb)
|
||||
RegisterNetEvent(cbEvent:format(name), function(resource, key, ...)
|
||||
event = cbEvent:format(name)
|
||||
|
||||
lib.setValidCallback(name, true)
|
||||
|
||||
RegisterNetEvent(event, function(resource, key, ...)
|
||||
TriggerClientEvent(cbEvent:format(resource), source, key, callbackResponse(pcall(cb, source, ...)))
|
||||
end)
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user