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:
29
package/shared/resource/cache/index.ts
vendored
29
package/shared/resource/cache/index.ts
vendored
@@ -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);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user