List all storage objects in a collection

Hello,

I’m trying to use nakama to get the number of times a level has been played.

I am using storage objects to store the number of plays.
The object is set with

Collection: LevelPlays,
Key: LevelName,
Value: {"Plays": \<Number of plays\>}

I need to populate the menu with the levels at runtime(since players can make new levels) and these menu objects need to show the play count on them.

Can I use the storage_list as a server RPC function to get all the play counts of all the levels and apply them to the menu objects?(Maybe something like concatenating the return value with all the play counts and separating them on the client side)

I noticed that there is a limit variable in the server_list server function. If I have more than 100 levels, how can I get across the limit? How do I use the cursor?

Listing operations are paginated to make sure you always get back only the required set of data, rather than get everything back and have to filter out a lot you may not need. Data is returned in “pages” and you can use cursors to get the next page or listing results.

Any non-nil cursor indicates there are more results beyond the current page. A nil cursor indicates your pagination has reached the end.

I’ll assume you want to paginate storage listings in an RPC function, try this:

local nk = require("nakama")

local function list_all(context, payload)
  local all_results = {}
  local next_cursor = nil
  repeat
    local results, cursor = nk.storage_list(nil, "LevelPlays", 100, next_cursor)
    for _, result in ipairs(results) do
      table.insert(all_results, result)
    end
    next_cursor = cursor
  until (not next_cursor)
  -- all_results now contains all records owned by the root user
  -- and that belong to collection "LevelPlays"

  return nk.json_encode(all_results)
end
nk.register_rpc(list_all, "list_all")

This is an example RPC function that will list all available records and return them, but you can of course just use the records internally in the RPC function rather than simply return them to the client/caller.

2 Likes