|
local function assign(dist, source) |
|
for k,v in pairs(source) do dist[k] = v end |
|
end |
|
|
|
M = {} |
|
|
|
local actions = {} |
|
actions.__mt = {} |
|
actions.__mt.__index = { |
|
method = 'GET', |
|
path = '/', |
|
headers = {}, |
|
body = {}, |
|
} |
|
|
|
function M.def_action(name) |
|
return function(options) |
|
setmetatable(options, actions.__mt) |
|
actions[name] = options |
|
end |
|
end |
|
|
|
function M.action(name) |
|
local action = {} |
|
setmetatable(action, { __index=actions[name] }) |
|
return action |
|
end |
|
|
|
M_prototype = {} |
|
|
|
function M_prototype:prepare(options) |
|
self.__prepare = options |
|
self.__actions_list = options |
|
end |
|
|
|
function M_prototype:actions(options) |
|
self.__actions = options |
|
self.__actions_list = self.__actions_list or options |
|
end |
|
|
|
function M_prototype:next_action() |
|
local idx = self.__idx |
|
if idx > #self.__actions_list then |
|
idx = 1 |
|
self.__actions_list = self.__actions |
|
end |
|
local action = self.__actions_list[idx] |
|
self.__idx = idx + 1 |
|
|
|
self.__current_before = action.before |
|
self.__current_after = action.after |
|
|
|
self.headers = self.headers or {} |
|
assign(self.headers, action.headers) |
|
|
|
self.body = {} |
|
assign(self.body, action.body) |
|
|
|
self.method = action.method |
|
self.path = action.path |
|
end |
|
|
|
function M_prototype:request() |
|
self:next_action() |
|
if self.__current_before ~= nil then |
|
self.__current_before(self) |
|
end |
|
return self.method, self.path, self.headers, self.body |
|
end |
|
|
|
function M_prototype:response(status, headers, body) |
|
if self.__current_after ~= nil then |
|
self.__current_after(self, status, headers, body) |
|
end |
|
end |
|
|
|
function M.m(o) |
|
o = o or {} |
|
o.__idx = 1 |
|
setmetatable(o, M_prototype) |
|
M_prototype.__index = M_prototype |
|
return o |
|
end |