Examples - leegeunhyeok/bxd Wiki

Examples

WIP

Demos

Basic

WIP

Transaction

WIP

Prepare a database

// 1. Create new BoxDB instance
const box = new BoxDB('bank', 1);

Create models

const User = box.model('user', {
  _id: {
    type: BoxDB.Types.NUMBER,
    key: true,
  },
  name: {
    type: BoxDB.Types.STRING,
    index: true,
  },
  amount: BoxDB.Types.NUMBER,
});

const History = box.model(
  'history',
  {
    fromUser: {
      type: BoxDB.Types.STRING,
      index: true,
    },
    toUser: {
      type: BoxDB.Types.STRING,
      index: true,
    },
    datetime: BoxDB.Types.DATE,
  },
  { autoIncrement: true },
);

Apply all registred models into IDB

await box.open(); // will create registered `user`, `post` object store

Data CRUD

// Method 1. Create empty data
const user1 = new User();
user1._id = 1;
user1.name = 'Emma';
user1.amount = 150;

// Method 2. Create data with initial value
const user2 = new User({
  _id: 2,
  name: 'Tom',
  amount: 50,
});

const user3 = new User({
  _id: 3,
  name: 'Unknown',
  amount: 0,
});

// Save data into `user` object store
await User.add(user1);
await User.add(user2);
await User.add(user3);
// Find data with a keyPath value of 1
const result = await User.get(1);

result; // { _id: 1, name: 'Emma', amount: 150 }
const result = await User.get(1);

// Update name field value (Emma to Jessica)
await User.put({
  ...result,
  name: 'Jessica',
});
// Delete data with a keyPath value of 3 (unknown user will be deleted)
await User.delete(3);
// Situation: Jessica sends $30 to Tom
const fromUser = await User.get(1); // Jessica
const toUser = await User.get(2); // Tom
const transactionAmount = 30;

// Resolve when all of tasks is done
// If any of the tasks fail, the transaction is aborted.
await box.transaction([
  User.task.put({
    ...fromUser,
    amount: fromUser.amount - transactionAmount,
  }),
  User.task.put({
    ...toUser,
    amount: toUser.amount + transactionAmount,
  }),
  History.task.add({
    fromUser: fromUser._id,
    toUser: toUser._id,
    datetime: new Date(),
  }),
]);

// Jessica: $120, Tom: $80
await box.transaction([
  AnyTask_1,
  AnyTask_2,
  BoxDB.interrupt(), // This transaction will be aborted
  AnyTask_3,
]);

// AnyTask_1, AnyTask_2, AnyTask_3 task not applied
// Rollback to before transaction