API

For reading and querying data stored in reorg-aware databases, API provide a faster, optimised approach. They allow for efficient retrieval of data and are ideal for powering your application’s infrastructure with speed and performance. If you need to frequently query or fetch data that has been indexed from the blockchain, these operations are the best fit, ensuring that your application can quickly access the necessary data.

import { Instance } from "@blockflow-labs/sdk";


Operations

The API Client in the Blockflow SDK enables read operations on already indexed data. Here are the available operations:

  • find: Retrieves all items from the database, with optional parameters like where, limit, and cache to refine the results.

  • findOne: Returns the most recent item that matches the specified parameters.

  • aggregate: Exclusive to MongoDB databases, this operation allows you to perform aggregation pipelines for more complex data processing.

  • query: Runs SQL queries on SQL-based databases. This operation does not work with MongoDB.


How to Use

To use the API Client in combination with MongoClient, you can set it up as shown in the example below. This code returns all the transfer events:

import { API } from "@blockflow-labs/sdk";

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

/**
 * @dev API
 * @param context object containing the response and request object
 * @param bind init function for database wrapper methods
 */
export const handler = async (context: any, bind: any) => {
  const { request, response } = context;

  const limit = request.query.limit || 10;

  const client = API.MongoClient(bind);

  const transferDB = client.db(Transfer);

  const data = await transferDB.find({
    where: {},
    take: Number(limit),
  });

  return data;
};

Last updated