-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.lua
More file actions
109 lines (94 loc) · 2.31 KB
/
app.lua
File metadata and controls
109 lines (94 loc) · 2.31 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
dofile("set_paths.lua")
local time = require("./time")
local _TK = time.start("request")
local cjson = require("cjson")
local inspect = require("inspect")
local io = require("io")
local lapis = require("lapis")
local config = require("lapis.config")
-- local console = require("lapis.console")
local pl = require("pl.import_into")()
local Api = require("./Api")
local bitser = require("./bitser")
local log = require("./log")
local pg = require("./pg")
local app = lapis.Application()
local _COUNT = 0
config(
{"develoment", "production"},
{
measure_performance = true
}
)
app:get(
"/",
function()
return "Welcome to Lapis " .. require("lapis.version")
end
)
local function interpretArg(s)
if s == "nil" then
return nil
end
local n = tonumber(s)
if n ~= nil then
return n
end
return n
end
local function handleApiRequest(self)
local body = ngx.req.read_body()
local bodyData = ngx.req.get_body_data()
local contentType = self.req.headers["content-type"]
local data
if contentType == "application/json" then
data = cjson.decode(bodyData)
elseif contentType == "application/x-lua+bitser" then
data = bitser.loads(bodyData)
else
error("Use content-type application/json or application/x-lua+bitser")
end
local tk = time.start()
a = Api(data.context)
local response = a:callMethod(data.method, data.args)
time.done(tk, "api." .. data.method .. cjson.encode(data.args))
if contentType == "application/json" then
return {json = response}
elseif contentType == "application/x-lua+bitser" then
return {
content_type = "application/x-lua+bitser",
layout = false,
bitser.dumps(response)
}
else
error("Use content-type application/json or application/x-lua+bitser")
end
end
app:post(
"/api",
function(self)
local tkc = time.start()
pg:connect()
time.done(tkc, "pg-connect")
local ok, errOrResult =
pcall(
function()
return handleApiRequest(self)
end
)
local tkk = time.start()
pg:keepalive()
time.done(tkk, "pg-keepalive")
if ok then
return errOrResult
else
-- TODO: Handle client error type things
log("An error: " .. errOrResult)
return {
status = 500,
json = "An error occurred: " .. errOrResult
}
end
end
)
return app