This repository has been archived by the owner on Jun 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 149
/
character.ts
338 lines (302 loc) · 9.11 KB
/
character.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import * as alt from 'alt-server';
import * as Athena from '@AthenaServer/api';
import { Character } from '@AthenaShared/interfaces/character';
import { KnownKeys } from '@AthenaShared/utility/knownKeys';
import { SYSTEM_EVENTS } from '@AthenaShared/enums/system';
import Database from '@stuyk/ezmongodb';
export type KeyChangeCallback = (player: alt.Player, newValue: any, oldValue: any) => void;
const callbacks: { [key: string]: Array<KeyChangeCallback> } = {};
const cache: { [id: string]: Character } = {};
const DEBUG_MODE = false; // Use this to see what state is being set.
/**
* Binds a player identifier to a Character document.
*
* This document is cleared on disconnected automatically.
*
* This should be the first thing you do after having a user authenticate and select a character.
*
* #### Example
*
* ```ts
* import Database from '@stuyk/ezmongodb';
*
* async function doSomething(somePlayer: alt.Player, someMongoDBId: string) {
* const someData = await Database.fetchData('_id', someMongoDBId, 'characters')
* Athena.document.character.bind(somePlayer, someData);
* }
* ```
*
* @param {alt.Player} player An alt:V Player Entity
* @param {Character} document
*/
export function bind(player: alt.Player, document: Character) {
if (Overrides.bind) {
return Overrides.bind(player, document);
}
if (document._id) {
document._id = document._id.toString();
}
cache[player.id] = document;
}
/**
* Unbind stored player character cache data.
*
* #### Example
*
* ```ts
* Athena.document.character.unbind(1);
* ```
*
*
* @param {number} id
*/
export function unbind(id: number) {
if (Overrides.unbind) {
return Overrides.unbind(id);
}
delete cache[id];
}
/**
* Return current player data and their associated character object.
*
* Can also append custom objects to the generic type to obtain custom data from the database.
*
* #### Example
* ```ts
* interface Testing {
* myProperty: string;
* }
*
* function someFunction(player: alt.Player) {
* const data = Athena.document.character.get<Testing>(player);
* if (typeof data === 'undefined') {
* // Player likely not logged in...
* return;
* }
*
* if (data.myProperty) {
* console.log(data.myProperty);
* }
* }
* ```
*
* @template T
* @param {alt.Player} player An alt:V Player Entity
* @return {T = Character}
*/
export function get<T = Character>(player: alt.Player): T | undefined {
if (Overrides.get) {
return Overrides.get(player);
}
return cache[player.id] as T;
}
/**
* Get the current value of a specific field inside of the player data object.
* Can be extended to obtain any value easily.
*
* #### Example
*
* Get a default value.
*
* ```ts
* const cash = Athena.document.character.getField<{}, number>(somePlayer, 'cash');
* if (typeof cash === 'undefined') {
* return;
* }
* ```
*
* Alternatively, pass a custom interface.
*
* ```ts
* interface CustomData {
* bitcoin: number
* }
*
* const bitcoins = Athena.document.character.getField<CustomData, number>(somePlayer, 'bitcoin');
* if (typeof bitcoins === 'undefined') {
* return;
* }
* ```
*
* @template T
* @param {alt.Player} player An alt:V Player Entity
* @param {(keyof KnownKeys<Character & T>)} fieldName
* @return {void}
*/
export function getField<T = {}, ReturnType = any>(
player: alt.Player,
fieldName: keyof KnownKeys<Character & T>,
): ReturnType | undefined {
if (Overrides.getField) {
return Overrides.getField(player, fieldName);
}
if (!cache[player.id]) {
return undefined;
}
return cache[player.id][String(fieldName)];
}
/**
* Sets a player document value, and saves it automatically to the selected character's database.
*
* Automatically calls all callbacks associated with the field name.
*
* #### Example
* ```ts
* await Athena.document.character.set(somePlayer, 'cash', 50);
* ```
*
* Alternatively, pass a custom interface.
*
* ```ts
* interface CustomCharacter {
* someKey: string;
* }
*
* await Athena.document.character.set<CustomCharacter>(somePlayer, 'someKey', 'hello world');
* ```
*
* @template T
* @param {alt.Player} player An alt:V Player Entity
* @param {(keyof KnownKeys<Character & T>)} fieldName
* @param {any} value
* @return {void}
*/
export async function set<T = {}, Keys = keyof KnownKeys<Character & T>>(
player: alt.Player,
fieldName: Keys,
value: any,
skipCallbacks = false,
) {
if (Overrides.set) {
return Overrides.set(player, fieldName, value, skipCallbacks);
}
if (!cache[player.id]) {
return undefined;
}
const typeSafeFieldName = String(fieldName);
let oldValue = undefined;
if (cache[player.id][typeSafeFieldName]) {
oldValue = JSON.parse(JSON.stringify(cache[player.id][typeSafeFieldName]));
}
const newData = { [typeSafeFieldName]: value };
cache[player.id] = Object.assign(cache[player.id], newData);
await Database.updatePartialData(cache[player.id]._id, newData, Athena.database.collections.Characters);
if (DEBUG_MODE) {
alt.logWarning(
`DEBUG: ${cache[player.id].name} state updated for ${typeSafeFieldName} with value: ${JSON.stringify(
newData,
)}`,
);
}
Athena.webview.emit(player, SYSTEM_EVENTS.PLAYER_EMIT_STATE, cache[player.id]);
if (typeof callbacks[typeSafeFieldName] === 'undefined') {
return;
}
if (skipCallbacks) {
return;
}
for (let cb of callbacks[typeSafeFieldName]) {
cb(player, value, oldValue);
}
}
/**
* Sets player document values, and saves it automatically to the selected character's database.
*
* Automatically calls all callbacks associated with the field name.
*
* #### Example
*
* ```ts
* await Athena.document.character.setBulk(player, { cash: 25, bank: 100 });
* ```
*
* @template T
* @param {alt.Player} player An alt:V Player Entity
* @param {(Partial<Character & T>)} fields
* @returns {void}
*/
export async function setBulk<T = {}, Keys = Partial<Character & T>>(player: alt.Player, fields: Keys) {
if (Overrides.setBulk) {
return Overrides.setBulk(player, fields);
}
const oldValues = {};
Object.keys(fields).forEach((key) => {
oldValues[key] = JSON.parse(JSON.stringify(cache[player.id][key]));
});
cache[player.id] = Object.assign(cache[player.id], fields);
await Database.updatePartialData(cache[player.id]._id, fields, Athena.database.collections.Characters);
Athena.webview.emit(player, SYSTEM_EVENTS.PLAYER_EMIT_STATE, cache[player.id]);
Object.keys(fields).forEach((key) => {
if (typeof callbacks[key] === 'undefined') {
return;
}
for (let cb of callbacks[key]) {
cb(player, cache[player.id][key], oldValues[key]);
}
});
}
/**
* Invokes the callback function when a document with a specific field name has changed.
*
* #### Example
* ```ts
* Athena.document.character.onChange('cash', (player: alt.Player, newValue: number, oldValue: number) => {
* // Do whatever you want with it.
* // Never, ever update the same document value twice in a row.
* // It creates an endless loop
* })
* ```
*
* @param {keyof KnownKeys<Character & T>} fieldName
* @param {KeyChangeCallback} callback
* @returns {void}
*/
export function onChange<T = {}>(fieldName: keyof KnownKeys<Character & T>, callback: KeyChangeCallback) {
if (Overrides.onChange) {
return Overrides.onChange(fieldName, callback);
}
const actualFieldName = String(fieldName);
if (typeof callbacks[actualFieldName] === 'undefined') {
callbacks[actualFieldName] = [callback];
} else {
callbacks[actualFieldName].push(callback);
}
}
alt.on('playerDisconnect', (player: alt.Player) => {
if (typeof player.id === 'undefined' || player.id === null) {
return;
}
const id = player.id;
if (!cache[id]) {
return;
}
Athena.player.events.trigger('player-disconnected', player, id, cache[id]);
unbind(id);
});
interface CharacterDocFuncs {
bind: typeof bind;
unbind: typeof unbind;
get: typeof get;
getField: typeof getField;
set: typeof set;
setBulk: typeof setBulk;
onChange: typeof onChange;
}
const Overrides: Partial<CharacterDocFuncs> = {};
export function override(functionName: 'bind', callback: typeof bind);
export function override(functionName: 'unbind', callback: typeof unbind);
export function override(functionName: 'get', callback: typeof get);
export function override(functionName: 'getField', callback: typeof getField);
export function override(functionName: 'set', callback: typeof set);
export function override(functionName: 'setBulk', callback: typeof setBulk);
export function override(functionName: 'onChange', callback: typeof onChange);
/**
* Used to override any character document functionality
*
*
* @param {keyof CharacterDocFuncs} functionName
* @param {*} callback
*/
export function override(functionName: keyof CharacterDocFuncs, callback: any): void {
Overrides[functionName] = callback;
}