porom/apps/api.lua

58 lines
1.7 KiB
Lua

local app = require("lapis").Application()
local json_params = require("lapis.application").json_params
local sse = require("lib.sse")
local db = require("lapis.db")
local html_escape = require("lapis.html").escape
local babycode = require("lib.babycode")
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)
app:post("babycode_preview", "/babycode-preview", json_params(function(self)
local user = util.get_logged_in_user(self)
if not user then
return {json = {error = "not authorized"}, status = 401}
end
if not util.rate_limit_allowed(user.id, "babycode_preview", 5) then
return {json = {error = "too many requests"}, status = 429}
end
local markup = self.params.markup
if not markup or type(markup) ~= "string" then
return {json = {error = "markup field missing or invalid type"}, status = 400}
end
local rendered = babycode.to_html(markup, html_escape)
return {json = {html = rendered}}
end))
return app