diff options
Diffstat (limited to 'store.lua')
| -rw-r--r-- | store.lua | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/store.lua b/store.lua new file mode 100644 index 0000000..b978b17 --- /dev/null +++ b/store.lua @@ -0,0 +1,77 @@ +local cqueues = require'cqueues' +local db = require'r.db' +local schema = require'r.db.schema' +local qw = require'r.qw' +local html = require'r.html' +local T = html.T +local class = require'r.class' +local App = require'r.web.app' +local server = require'r.web.server' + +local Queue = require'queue' +local Log = require'log' + +local Store = class() -- we only have 1 instance of this, but, ough, +function Store.make(cls) + schema.schemafy { + messages = { + {"p_type","text",not nil}, + {"p_name","text",not nil}, + {"channel","text",not nil}, + {"author","text",not nil}, + {"ts","text",not nil}, + {"body","text"}, + }, + } + return setmetatable({ + q = Queue(), + log = Log"store", + },cls) +end + +function Store.storing(self) + local conn = db.conn() + for msg in self.q:iter() do + -- needs to go in its own coro + -- so we don't gum up the works while waiting on the db + conn:exec([[ + insert into messages (p_type, + p_name,channel,author,ts,body) + values (?, ?, ?, ?, ?, ?); ]], + msg.pylon.type,msg.pylon.name, + msg.channel.id, msg.author.id, + os.time(),msg.body) + self.log("stored",msg.body) + assert(conn:commit()) end end +function Store.store(self, msg) self.q:enqueue(msg) end + +local function view(req) + local conn <close> = db.conn() + local rows = conn:fetch"select * from messages order by ts asc;" + local fields = qw"id p_type p_name channel author ts body" + -- list comprehensions? WHAT ARE THOSE????? + local ths={} for i,v in ipairs(fields) do ths[i]=T.th(v) end + local trs={} for ri,r in ipairs(rows) do + local tds = {} for i,v in ipairs(fields) do tds[i]=T.td(r[v]) end + trs[ri] = T.tr(tds) end + local tab = T.table{ + T.thead(T.tr(ths)), + T.tbody(trs), + } + return html.html { + T.h1'the messages', + tab + } end +local app = App{ view = view } +function Store.serving(self) + return server.run(self.cq, app) end + +function Store.run(self) + self.cq = cqueues.new() + self.cq:wrap(self.storing, self) + self.cq:wrap(self.serving, self) + self.log("now running") + self.log:loop(self.cq) +end + +return Store |
