porom/apps/api.lua

37 lines
966 B
Lua

local app = require("lapis").Application()
local sse = require("lib.sse")
local db = require("lapis.db")
local util = require("util")
app:get("sse_thread_updates", "/thread-updates/:thread_id", function(self)
do
local thread = db.query("SELECT threads.id FROM threads WHERE threads.id = ?", self.params.thread_id)
if #thread == 0 then
return {status = 404, skip_render = true}
end
end
local now = os.time()
local stream = sse:new()
local thread_id = self.params.thread_id
local new_posts_query = "SELECT id FROM posts WHERE thread_id = ? AND posts.created_at > ? ORDER BY posts.created_at ASC LIMIT 1"
while stream.active do
stream:dispatch()
local new_post = db.query(new_posts_query, thread_id, now)
if #new_post > 0 then
local url = util.get_post_url(self, new_post[1].id)
stream:enqueue(url, "new_post_url")
end
ngx.sleep(5)
end
return {skip_render = true}
end)
return app