-
Notifications
You must be signed in to change notification settings - Fork 1
2. Sync Data
Stuyk edited this page Jul 2, 2023
·
3 revisions
When you have an account or a character you want to bind to a player's session that is when you use crc.data.sync
.
This allows for values to easily be set
and get
.
This means that you can set values such as cash
, bank
, appearance
, etc. to the database for your player.
You usually want to sync
a player after they have logged in.
- This can be after login
- This can also be after login, and after selecting a character
You should only call sync
on a player one time.
Pretty much anything that uses alt.Entity
can be auto-synchronized with updates to the database.
- alt.Player
- alt.Vehicle
- alt.Ped
- alt.Colshape
- alt.Checkpoint
- etc.
crc.data.sync(player, documentID, 'mytable');
The example below shows how to login / register and also apply data synchronization for a single account.
import * as crc from '@stuyk/cross-resource-cache';
interface Account {
_id?: string;
username: string;
password: string;
}
const COLLECTION_NAME = 'account';
async function createAccount(username: string, password: string) {
// Protected plain text password in-database
const passwordHash = crc.utility.password.create(password);
// This creates a new document for the username and uses the hashed password.
const documentID = await crc.database.create<Account>(
{ id: data.id, username, password: passwordHash },
COLLECTION_NAME
);
return await crc.database.get<I.Account>({ _id: documentID }, COLLECTION_NAME);
}
async function loginOrRegister(player: alt.Player, username: string, password: string) {
// Lookup account by username
let account: Account = await crc.database.get<Account>({ username }, COLLECTION_NAME);
if (!account) {
account = await createAccount(username, password);
}
// Check if the password matches, if not cancel
if (!crc.utility.password.check(password, account.password)) {
// Add cancel logic here...
return;
}
// Synchronize the player to use this single-account for all database writes for this player
crc.data.sync(player, account._id, COLLECTION_NAME);
}