mirror of
https://github.com/CommunityOx/ox_lib.git
synced 2026-08-17 06:56:03 +01:00
feat(cache): send oldValue to onCache
Internally handle the cache events to prevent race conditions and resolve #618. Improved types.
This commit is contained in:
28
init.lua
28
init.lua
@@ -91,9 +91,6 @@ end
|
||||
local lib = setmetatable({
|
||||
name = ox_lib,
|
||||
context = context,
|
||||
onCache = function(key, cb)
|
||||
AddEventHandler(('ox_lib:cache:%s'):format(key), cb)
|
||||
end
|
||||
}, {
|
||||
__index = call,
|
||||
__call = call,
|
||||
@@ -173,14 +170,27 @@ end
|
||||
---Caches the result of a function, optionally clearing it after timeout ms.
|
||||
function cache(key, func, timeout) end
|
||||
|
||||
local cacheEvents = {}
|
||||
|
||||
local cache = setmetatable({ game = GetGameName(), resource = resourceName }, {
|
||||
__index = context == 'client' and function(self, key)
|
||||
__index = function(self, key)
|
||||
cacheEvents[key] = {}
|
||||
|
||||
AddEventHandler(('ox_lib:cache:%s'):format(key), function(value)
|
||||
local oldValue = self[key]
|
||||
local events = cacheEvents[key]
|
||||
|
||||
for i = 1, #events do
|
||||
Citizen.CreateThreadNow(function()
|
||||
events[i](value, oldValue)
|
||||
end)
|
||||
end
|
||||
|
||||
self[key] = value
|
||||
end)
|
||||
|
||||
return rawset(self, key, export.cache(nil, key) or false)[key]
|
||||
end or nil,
|
||||
end,
|
||||
|
||||
__call = function(self, key, func, timeout)
|
||||
local value = rawget(self, key)
|
||||
@@ -197,6 +207,14 @@ local cache = setmetatable({ game = GetGameName(), resource = resourceName }, {
|
||||
end,
|
||||
})
|
||||
|
||||
function lib.onCache(key, cb)
|
||||
if not cacheEvents[key] then
|
||||
getmetatable(cache).__index(cache, key)
|
||||
end
|
||||
|
||||
table.insert(cacheEvents[key], cb)
|
||||
end
|
||||
|
||||
_ENV.cache = cache
|
||||
|
||||
local notifyEvent = ('__ox_notify_%s'):format(cache.resource)
|
||||
|
||||
Reference in New Issue
Block a user