-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path_Api.lua
More file actions
119 lines (106 loc) · 2.58 KB
/
_Api.lua
File metadata and controls
119 lines (106 loc) · 2.58 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
local pl = require('pl.import_into')()
local Object = require("classic")
local _Api = Object:extend()
function _Api:new(context)
self.context = context
self.response = {
result = nil,
error = nil,
data = {},
cmd = {}
}
end
local function startsWith(s, prefix)
if type(s) ~= "string" then
return false
end
return string.sub(s, 1, string.len(prefix)) == prefix
end
local function slice(t, start, fin)
return {table.unpack(t, start, fin)}
end
function _Api:callMethod(method, args)
if not self.response then
self.response = {}
end
if startsWith(method, "_") or method == "super" or _Api[method] ~= nil then
self.response.error = {
type = "API_ERROR",
code = "RESERVED_METHOD_NAME",
message = "The method `" .. method .. "` is a reserved method name",
props = {
method = method
}
}
return self.response
end
if not Api[method] then
self.response.error = {
type = "API_ERROR",
code = "NOT_IMPLEMENTED",
message = "No such method `" .. method .. "` in the API",
props = {
method = method
}
}
return self.response
end
local ok, resultOrErr = pcall(Api[method], self, table.unpack(args))
if ok then
self.response.result = resultOrErr
self.response.error = nil
else
local start, fin = string.find(resultOrErr, ": ")
local err = string.sub(resultOrErr, fin + 1)
local pos, len = string.find(err, "[%u%d_%d:]+:")
if pos == nil or pos ~= 1 then
self.response.error = {
type = nil,
code = nil,
message = resultOrErr,
props = nil
}
else
local prefix = string.sub(err, pos, len)
local rest = string.sub(err, pos + len)
local parts = pl.stringx.split(prefix, ":")
if #parts == 1 then
self.response.error = {
type = parts[1],
code = nil,
message = rest
}
elseif #parts == 2 then
self.response.error = {
type = parts[1],
code = parts[2],
message = rest,
props = nil
}
else
self.response.error = {
type = parts[1],
code = parts[2],
message = rest,
etc = slice(parts, 3),
props = nil
}
end
end
end
return self.response
end
function _Api:setData(key, val)
if type(key) == "table" then
for k, v in pairs(key) do
self:setData(k, v)
end
return
else
self.response.data[key] = val
end
end
function _Api:addCommand(cmd)
table.insert(self.response.data, cmd)
end
return _Api