05 / 11Beginner
Comparing frontends
This lesson shows how a frontend client calls the Web2 REST API and how that compares with sending transactions and queries to the Chromia Web3 dapp.
Web2 frontend with Axios
The Web2 app has a REST API, but users need a frontend with an interface to work with it. Below is one way to call the API from JavaScript. The native Fetch API would work, but the example uses the Axios library because it keeps the code a little tidier:
// frontend.jsimport axios from "axios";// Base URL for the APIconst API_BASE_URL = "http://localhost:3000";// Create a userfunction createUser(name, id) { return axios .post(`${API_BASE_URL}/users`, { name, id }) .then((response) => response.data);}// Create a postfunction createPost(userId, content) { return axios .post(`${API_BASE_URL}/posts`, { userId, content }) .then((response) => response.data);}// Fetch users with paginationfunction fetchUsers(offset = 0, limit = 10) { return axios .get(`${API_BASE_URL}/users`, { params: { offset, limit }, }) .then((response) => response.data);}// Example Usage:// createUser('John Doe', 'unique_id_as_byte_array');// createPost('USER_OBJECT_ID_HERE', 'This is a post content.');// fetchUsers();Most web developers will recognize this pattern. The next example does the same thing on the Chromia platform.
Web3 Frontend with Chromia's postchain-client
On Chromia, you change data by sending transactions to the Chromia blockchain network. The Chromia TypeScript client library, postchain-client, handles this for you.
The following code uses postchain-client to send transactions that match the earlier REST API calls:
import { createClient } from "postchain-client";// Our dapp's unique ID when deployed to the Chromia network. We get this when// we deploy our dapp.const blockchainRid = "...";// URLs to system nodes in the Chromia network. These are automatically queried by the// client library to find the URLs of the specific nodes running our particular dapp.const directoryNodeUrlPool = ["url1", "url2", "url3", "etc."];const chromiaClient = await createClient({ directoryNodeUrlPool, blockchainRid,});// Create a userfunction createUser(name, id) { return chromiaClient.sendTransaction( { name: "create_user", args: [name, id], } );}// Create a postfunction createPost(userId, content) { return chromiaClient.sendTransaction( { name: "make_post", args: [userId, content], } );}// Example Usage:// createUser('John Doe', 'unique_id_string');// createPost('USER_OBJECT_ID_HERE', 'This is a post content.');Fetching users through the get_users query from the dapp backend doesn't require a transaction. You only need transactions, which are almost always signed with cryptographic keys, when you change data. Call the read-only query like this:
const users = await chromiaClient.query("get_users", { pointer: 0, n_users: 10,});The next lesson covers adding authentication and authorization to the dapp.