Dimension Life (DL) has 4 Read Handler
: getPet
、getCount
、getTopPets
、checkNameUnique
、Info
(for process information).
Let’s check them on by one and use aos to interact with DL Process.
First, Let' sent DL process id in aos (can use any process):
DL = "cO4thcoxO57AflN5hfXjce0_DydbMJclTU9kC3S75cg"
getPet
This is a query of one Pet given address (index of pet)
We can send the message in aos:
Send({ Target = DL, Action = "getPet", Data = '{"address": "0x01100"}' })
Let’s analysis the source code:
local json = require("json")
...
-- Function to execute SQL queries and return results
local function query(stmt)
local rows = {}
for row in stmt:nrows() do
table.insert(rows, row)
end
stmt:reset()
return rows
end
...
-- Function to get a pet by address
local function getPet(data)
local dataJson = json.decode(data)
local address = dataJson.address
local stmt = DB:prepare [[
SELECT * FROM pets WHERE address = :address;
]]
if not stmt then
error("Failed to prepare SQL statement: " .. DB:errmsg())
end
stmt:bind_names({ address = address })
local rows = query(stmt)
return rows
end
...
-- Send({ Target = ao.id, Action = "getPet", Data = '{"address": "0x01100"}' })
-- Add getPet Handler
Handlers.add(
"getPet",
Handlers.utils.hasMatchingTag("Action", "getPet"),
function (msg)
local pet = getPet(msg.Data)
local petsJson = json.encode(pet)
print(pet)
Handlers.utils.reply(petsJson)(msg)
end
)
The json module is imported to provide json.encoding function
local json = require("json")
The code that handles the query is
-- Send({ Target = ao.id, Action = "getPet", Data = '{"address": "0x01100"}' })
-- Add getPet Handler
Handlers.add(
"getPet",
Handlers.utils.hasMatchingTag("Action", "getPet"),
function (msg)
local pet = getPet(msg.Data)
local petsJson = json.encode(pet)
print(pet)
Handlers.utils.reply(petsJson)(msg)
end
About Handler
Hanler.add
has three parameters:name
,pattern
and handler
💡 Ref:
https://cookbook_ao.arweave.dev/references/handlers.html