You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
2.3 KiB
66 lines
2.3 KiB
-- Lua-side of the http module.
|
|
-- http.request (stateless) and http.session (constructor) are provided by Rust
|
|
-- before this runs. This layer adds resp.json(), method shorthands, the
|
|
-- JSON/postJSON helpers, and a metatable for session objects.
|
|
|
|
-- Attach resp.json() to a response table: parses resp.body via utils.fromJSON.
|
|
local function wrap_resp(resp)
|
|
resp.json = function() return utils.fromJSON(resp.body) end
|
|
return resp
|
|
end
|
|
|
|
-- Wrap the stateless http.request so responses carry resp.json().
|
|
local _request = http.request
|
|
http.request = function(method, url, opts)
|
|
return wrap_resp(_request(method, url, opts))
|
|
end
|
|
|
|
-- Method shorthands for the stateless module.
|
|
for _, m in ipairs({ "get", "post", "put", "patch", "delete", "head" }) do
|
|
http[m] = function(url, opts) return http.request(m:upper(), url, opts) end
|
|
end
|
|
|
|
function http.getJSON(url, opts)
|
|
local resp = http.get(url, opts)
|
|
return resp.json(), resp
|
|
end
|
|
|
|
function http.postJSON(url, body, opts)
|
|
opts = opts or {}
|
|
opts.json = body
|
|
return http.post(url, opts)
|
|
end
|
|
|
|
-- Session metatable. http.session() returns a raw Rust table whose methods are
|
|
-- _request, save, load, clearCookies and cookies. The metatable adds the
|
|
-- request wrapper (for resp.json()) and the method shorthands on top.
|
|
local session_mt = {}
|
|
session_mt.__index = session_mt
|
|
|
|
function session_mt:request(method, url, opts)
|
|
return wrap_resp(self:_request(method, url, opts))
|
|
end
|
|
|
|
function session_mt:get(url, opts) return self:request("GET", url, opts) end
|
|
function session_mt:post(url, opts) return self:request("POST", url, opts) end
|
|
function session_mt:put(url, opts) return self:request("PUT", url, opts) end
|
|
function session_mt:patch(url, opts) return self:request("PATCH", url, opts) end
|
|
function session_mt:delete(url, opts) return self:request("DELETE", url, opts) end
|
|
function session_mt:head(url, opts) return self:request("HEAD", url, opts) end
|
|
|
|
function session_mt:getJSON(url, opts)
|
|
local resp = self:get(url, opts)
|
|
return resp.json(), resp
|
|
end
|
|
|
|
function session_mt:postJSON(url, body, opts)
|
|
opts = opts or {}
|
|
opts.json = body
|
|
return self:post(url, opts)
|
|
end
|
|
|
|
-- Wrap the Rust session constructor to install the metatable.
|
|
local _session = http.session
|
|
http.session = function(path)
|
|
return setmetatable(_session(path), session_mt)
|
|
end
|
|
|