Skip to content

Commit

Permalink
feat(PE-6331): support paginated records (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
dtfiedler authored Jul 10, 2024
2 parents 74ca664 + 7f3fddf commit 5d46ce4
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/arns.lua
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,36 @@ function arns.addRecord(name, record)
end
end

function arns.getSortedRecords(page, pageLimit, sortBy, sortDirection)
local records = arns.getRecords()
-- sort the reocrds map by the keys alphabeticcally
local sortedRecords = {}
for name, record in pairs(records) do
record.name = name
table.insert(sortedRecords, record)
end

-- sort the records by the named
table.sort(sortedRecords, function(recordA, recordB)
local nameAString = recordA[sortBy]
local nameBString = recordB[sortBy]
if sortDirection == "desc" then
nameAString, nameBString = nameBString, nameAString
end
return nameAString < nameBString
end)

return {
records = utils.slice(sortedRecords, (page - 1) * pageLimit + 1, page * pageLimit),
page = page,
totalItems = #sortedRecords,
totalPages = math.ceil(#sortedRecords / pageLimit),
sortBy = sortBy,
sortDirection = sortDirection,
hasNextPage = page * pageLimit < #sortedRecords,
}
end

function arns.extendLease(from, name, years, currentTimestamp)
local record = arns.getRecord(name)
-- throw error if invalid
Expand Down
9 changes: 9 additions & 0 deletions src/main.lua
Original file line number Diff line number Diff line change
Expand Up @@ -1274,6 +1274,15 @@ Handlers.add("addReservedName", utils.hasMatchingTag("Action", "AddReservedName"
end
end)

Handlers.add("paginatedRecords", utils.hasMatchingTag("Action", "Paginated-Records"), function(msg)
local page = tonumber(msg.Tags.Page) or 1
local pageLimit = tonumber(msg.Tags["Page-Size"]) or 10
local sortOrder = msg.Tags.SortOrder and string.lower(msg.Tags["Sort-Order"]) or "asc"
local sortBy = msg.Tags.SortBy and string.lower(msg.Tags["Sort-By"]) or "name"
local sortedRecords = arns.getSortedRecords(page, pageLimit, sortBy, sortOrder)
ao.send({ Target = msg.From, Data = json.encode(sortedRecords) })
end)

-- END UTILITY HANDLERS USED FOR MIGRATION

return process
9 changes: 9 additions & 0 deletions src/utils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@ function utils.isInteger(value)
return value % 1 == 0
end

function utils.slice(tbl, first, last, step)
local sliced = {}

for i = first or 1, last or #tbl, step or 1 do
sliced[#sliced + 1] = tbl[i]
end

return sliced
end
function utils.isValidArweaveAddress(address)
return #address == 43 and string.match(address, "^[%w-_]+$") ~= nil
end
Expand Down

0 comments on commit 5d46ce4

Please sign in to comment.