Files
ox_lib/imports/callback/server.lua
T

64 lines
1.5 KiB
Lua
Raw Normal View History

2022-06-09 05:15:27 +10:00
local events = {}
2022-06-09 04:43:37 +10:00
local cbEvent = ('__cb_%s'):format(cache.resource)
2022-02-28 16:30:58 +11:00
2022-06-09 05:15:27 +10:00
RegisterNetEvent(cbEvent, function(key, ...)
local cb = events[key]
return cb and cb(...)
end)
---@param _ any
---@param event string
---@param playerId number
---@param cb function
---@param ... unknown
---@return unknown
local function triggerClientCallback(_, event, playerId, cb, ...)
local key
repeat
key = ('%s:%s:%s'):format(event, math.random(0, 100000), playerId)
until not events[key]
TriggerClientEvent(('__cb_%s'):format(event), playerId, key, ...)
local promise = not cb and promise.new()
events[key] = function(response)
events[key] = nil
if promise then
return promise:resolve(response)
end
cb(table.unpack(response))
end
if promise then
return table.unpack(Citizen.Await(promise))
end
end
---@overload fun(event: string, playerId: number, cb: function, ...)
local callback = setmetatable({}, {
__call = triggerClientCallback
})
---@param event string
---@param playerId number
--- Sends an event to a client and halts the current thread until a response is returned.
function callback.await(event, playerId, ...)
return triggerClientCallback(_, event, playerId, false, ...)
end
2022-02-28 16:30:58 +11:00
---@param name string
2022-03-10 14:23:25 +00:00
---@param cb function
2022-02-28 16:30:58 +11:00
--- Registers an event handler and callback function to respond to client requests.
2022-02-28 17:14:18 +11:00
function callback.register(name, cb)
name = ('__cb_%s'):format(name)
2022-02-28 16:30:58 +11:00
2022-06-09 05:15:27 +10:00
RegisterNetEvent(name, function(key, ...)
2022-06-09 04:43:37 +10:00
TriggerClientEvent(cbEvent, source, key, { cb(source, ...) })
2022-02-28 16:30:58 +11:00
end)
end
2022-02-28 17:14:18 +11:00
return callback