Creating and Destroying Resources

Store lua scripts as Resources that can link to arbitrary paths and access functions in your game or application.

Resources are Lua scripts that you can create and store on disk that let you link to arbitrary paths and access functions.

For example, if you had a game in which you wanted to link to two players, you might have code similar to this:

-- game_script.lua
local resource = require "namazu.resource"

local game_script = {}

-- Save the player ids to the resource
function game_script.set_player_ids(p1_id, p2_id)

    game_script.player1_id = p1_id
    game_script.player2_id = p2_id

    -- Serialize this resource to disk after the changes have been made
    resource.commit()

end

return game_script


-- Endpoint code

local util = require "namazu.util"
local index = require "namazu.index"
local resource = require "namazu.resource"
local response = require "namazu.response"
local responsecode = require "namazu.response.code"

local game_api = {}

function game_api.create_game(payload, request, session)

    -- Since this is an authenticated request, we can get the requesting
    -- player's profile directly
    local p1_profile = auth.profile()
    local player1_id = p1_profile.id

    -- Payload is the profile id of player 2 in this example
    local player2_id = payload

    -- We want to make sure that the new game's path is unique
    local game_id = util.uuid()

    -- The creation path can be anything, but using derived values
    -- (such as the player ids) makes it easier to access again in the future
    local creation_path = string.format("games/%s/%s/%s", player1_id, player2_id, game_id)

    local resource_id, response_code = resource.create("game_script", creation_path)

    -- Make sure that the create request was successful!
    if(response_code == responsecode.OK) then

        -- Link player 2 to the game resource
        local link_path = string.format("games/%s/%s/%s", player2_id, player1_id, game_id)

        response_code = index.link(resource_id, link_path)

        -- Make sure that the link was successful!
        if(response_code == responsecode.OK) then

            -- Invoke the function set_player_ids(p1_id, p2_id) 
            -- on our instance of game_script.lua
            resource.invoke(resource_id, "set_player_ids", player1_id, player2_id)

            return response.formulate(200)

        end

        -- The link was unsuccessful, so we destroy the resource so
        -- that it doesn't linger on disk. This rarely happens but it's
        -- good to handle!
        resource.destroy(resource_id)
    end

    -- Something went wrong along the way
    return response.formulate(400)
end

return game_api

In addition to resource.destroy(resource_id), a resource can be destroyed if all links are removed using index.unlink(path).

Now that we have created a resource, we can get into accessing its functions.

Last updated