Create and Update Record

Before using functions like .save, .findOne, and .create to interact with the database, you need to establish a connection between the subgraph and the chosen database. This connection is facilitated by the bind function.

import { Transfer } from "../../types/schema";

Class is imported from generated schema.ts file.

const transferDB: Instance = bind(Transfer);

Now your DB is loaded and you can perform all CRUD operations.


CRUD Operations

Blockflow cli is inspired by the Mongoose. The store supports the following methods.

  • create

  • find

  • findOne

  • deleteOne

  • updateOne

  • save


create

This function is used to create a new instance of an entity in the database. It takes an object representing the entity data as an argument and returns the newly created entity instance.

let entityId = transaction.transaction_hash + "-" + log.log_index;

let entity: ITransfer = await transferDB.create({
    id: entityId,
    from: from.toString(),
    to: to.toString(),
    amount: value.toString(),
  });

When creating a new entity instance, it is recommended to initialize all the fields defined in the schema with their respective default values. This practice ensures data consistency and helps avoid potential issues caused by uninitialized fields.


find

This function retrieves an array of entities from the database based on specified filter criteria. It takes an object containing the filter conditions as an argument and returns an array of matching entities.

let entities: ITransfer[] = await transferDB.find({
    amount: "0",
});


findOne

This function allows you to retrieve a single entity instance from the database based on specified criteria. In the example below, the function will return an entity with the specified id, and the returned entity will have the same type as ITransfer, ensuring type safety.

let entityId = transaction.transaction_hash + "-" + log.log_index;

let entity: ITransfer = await transferDB.findOne({ id: entityId });


deleteOne

This function removes a single entity from the database based on specified filter criteria. It takes an object containing the filter conditions as an argument.

await transferDB.deleteOne({ id: entityId });


updateOne

This function updates a single entity in the database based on provided filter criteria and update data. It takes two objects as arguments: the first object specifies the filter conditions, and the second object contains the updated field values. It returns the updated entity.

await transferDB.updateOne({ id: entityId }, {
    amount: "0"
});

You only need to pass the updated fields in the second argument (the update document), and this will update only those specified fields while leaving the other fields unchanged.


save

This function is used to save or update an entity instance in the database. It takes an entity object as an argument and persists the data accordingly.

await transferDB.save(entity);