Skip to main content

Query the blockchain with postchain-client

In this section, we'll look into querying the Chromia blockchain to retrieve information about transactions and our dapp table state.

Queuing using postchain-client is really simple; let's look at an example that fetches all books and then breaks them down.

First, we need to add a type for Book to hold our book information:

type Book = {
isbn: string;
title: string;
author: string;
};

Then, we add a function to fetch and list all books.

const getAllBooks = async () => {
const bookList = await client.query<Book[]>("get_all_books", {});
console.log("Book list\n", bookList);
};

In this function we use the client and the query command to execute our query. We define the return type as a generic type, in this case Book[].

Then we add the arguments:

First Argument queryFunctionName:

This is the name of the query function defined on the blockchain. It corresponds to a function in a Rell script responsible for retrieving all book records.

Second Argument queryArguments:

An empty object ({}) signifies that this query doesn't require any specific arguments to function. This object could contain parameters the blockchain function uses to filter or process results if necessary.

Handling the response

The client.query method returns a promise that, when resolved, yields an array of books (Book[]). These retrieved books can then be displayed, processed, or used in any other way according to your app's needs. In this example, we output the result to the console.

We can add getAllBooks(); to our main function, resulting in the function below. Now, you can re-run the client and see that we also list our added book. To re-run the example code, you can use the command chr node start --wipe to start with a new node without any data.

async function main() {
client = await createClient({
nodeUrlPool: "http://localhost:7740",
blockchainRid: blockchainRID,
});

console.log("Creating a new book transactions");
await client.signAndSendUniqueTransaction(
{ name: "create_book", args: ["ISBN1", "Chromia 101", "John Doe"] },
bookKeeperSignatureProvider
);

getAllBooks();
}