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:
Linden
2024-08-13 14:11:27 +10:00
parent 03db59cce5
commit 6b12831817
2 changed files with 49 additions and 8 deletions

View File

@@ -1,13 +1,34 @@
export const cache: Record<string, any> = new Proxy(
interface OxCache {
ped: number;
vehicle: number | false;
seat: number | false;
game: string;
resource: string;
playerId: number;
serverId: number;
[key: string]: unknown;
}
const cacheEvents: Record<keyof OxCache, Function[]> = {};
export const cache: OxCache = new Proxy(
{
resource: GetCurrentResourceName(),
game: GetGameName(),
},
{
get(target: any, key: string) {
const result = key ? target[key] : target;
if (result !== undefined) return result;
cacheEvents[key] = [];
AddEventHandler(`ox_lib:cache:${key}`, (value: any) => {
const oldValue = target[key];
const events = cacheEvents[key];
events.forEach((cb) => cb(value, oldValue));
target[key] = value;
});
@@ -17,6 +38,8 @@ export const cache: Record<string, any> = new Proxy(
}
);
export const onCache = <T = any>(key: string, cb: (value: T) => void) => {
AddEventHandler(`ox_lib:cache:${key}`, cb);
export const onCache = <T extends keyof OxCache>(key: T, cb: (value: OxCache[T], oldValue: OxCache[T]) => void) => {
if (!cacheEvents[key]) cache[key];
cacheEvents[key].push(cb);
};