Skip to content

3. Read, Write, and Create

Stuyk edited this page Jul 2, 2023 · 3 revisions

This section covers the basic operations of reading, writing, and creating data in various collections.

It also covers exactly how to use sync data so that it auto-writes to database on set for individual entities.

Read Data

After applying a document to a player with crc.data.sync you can get values.

const result = await crc.data.getValue<string>(player, 'something');
console.log(result);

Write Data

After applying a document to a player with crc.data.sync you can set values.

await crc.data.setValue(player, 'something', 'hello world!');

Sync Example

The example below shows adding banking functions after assigning a document with crc.data.sync,

async function addBank(player: alt.Player, amount: number) {
    amount = Math.abs(amount);

    let originalValue = crc.data.getValue<number>(player, 'bank');
    if (!originalValue) {
        originalValue = 0;
    }

    await crc.data.setValue(player, 'bank', originalValue + amount);
}

async function subBank(player: alt.Player, amount: number) {
    amount = Math.abs(amount);

    let originalValue = crc.data.getValue<number>(player, 'bank');
    if (!originalValue || originalValue - amount < 0) {
        console.log(`removal request exceeded bank balance`);
        return;
    }

    await crc.data.setValue(player, 'bank', originalValue - amount);
}

Custom

If you need custom collections, data, etc. then this section is for you.

Create Data

This shows you how to create a new document for some data.

It always returns an _id which can be used to fetch the full document after creation.

interface Example {
    _id?: string;
    test?: string;
}

...

// Creates the data with an initial value for 'test'
// Returns the documentID which can be fetched or stored somewhere
const documentID = await crc.database.create<Example>({ test: 'hi' }, 'mytable');

Update Data

This shows you how to update an existing document, if you have the _id of that document.

interface Example {
    _id?: string;
    test?: string;
    newValue?: string;
}

...

const someDocument = await crc.database.get<Example>({ _id: documentID }, 'mytable');
if (!someDocument) {
  throw new Error(`Document does not exist with id: ${documentID}`);
}

// Document will now have _id, test, and newValue
await crc.database.update<Example>({ _id: someDocument._id, newValue: 'hi' });

Example

The example below shows how to create a collection called account which works with regular username / password based logins.

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>(
        { 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;
    }

    // the variable `account` belongs to the player that connected
    // do something else with the account
    console.log(account)
}
Clone this wiki locally