-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.lua
59 lines (51 loc) · 1.48 KB
/
http.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
local function response_wrapper(res)
return {
code = res.code,
json = function()
return Promise.resolved(minetest.parse_json(res.data))
end,
text = function()
return Promise.resolved(res.data)
end
}
end
function Promise.http(http, url, opts)
assert(http, "http instance is nil")
assert(url, "no url given")
-- defaults
opts = opts or {}
return Promise.new(function(resolve, reject)
local extra_headers = {}
local data = opts.data
if type(data) == "table" then
-- serialize as json
data = minetest.write_json(data)
table.insert(extra_headers, "Content-Type: application/json")
end
for _, h in ipairs(opts.headers or {}) do
table.insert(extra_headers, h)
end
http.fetch({
url = url,
extra_headers = extra_headers,
timeout = opts.timeout or 10,
method = opts.method or "GET",
data = data
}, function(res)
if res.succeeded then
resolve(response_wrapper(res))
else
reject(res)
end
end)
end)
end
function Promise.json(http, url, opts)
return Promise.http(http, url, opts):next(function(res)
if res.code == 200 then
return res.json()
else
return Promise.rejected("unexpected status-code: " .. res.code)
end
end)
end