From af8cd453bf63bea136d2b4a71c783ef5542a05ed Mon Sep 17 00:00:00 2001 From: rebecca Date: Thu, 17 Sep 2026 22:13:53 +0100 Subject: implement rudimentary message storing system --- store.lua | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 store.lua (limited to 'store.lua') diff --git a/store.lua b/store.lua new file mode 100644 index 0000000..a970fcb --- /dev/null +++ b/store.lua @@ -0,0 +1,59 @@ +local cqueues = require'cqueues' +local db = require'r.db' +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) 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 (ts, body) values (?,?);", + 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 = db.conn() + local rows = conn:fetch"select * from messages order by ts asc;" + local fields = qw"id 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 -- cgit v1.2.3