Mercurial Hosting > disearch
diff src/lib/Server.luan @ 13:af2b95854072
add server records
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Mon, 30 Oct 2023 21:32:42 -0600 |
parents | |
children | 80105b716a62 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/lib/Server.luan Mon Oct 30 21:32:42 2023 -0600 @@ -0,0 +1,84 @@ +local Luan = require "luan:Luan.luan" +local error = Luan.error +local ipairs = Luan.ipairs or error() +local Db = require "site:/lib/Db.luan" +local Utils = require "site:/lib/Utils.luan" +local get_user = Utils.get_user or error() + + +local Server = {} + +local function from_doc(doc) + doc.type == "server" or error "wrong type" + return Server.new { + id = doc.id + owner_discord_id = doc.server_owner_discord_id + discord_id = doc.discord_id + name = doc.name + icon = doc.icon + invite = doc.invite + } +end + +local function to_doc(server) + return { + type = "server" + id = server.id + server_owner_discord_id = server.owner_discord_id or error() + discord_id = server.discord_id or error() + name = server.name or error() + icon = server.icon or error() + invite = server.invite or error() + } +end + +function Server.new(server) + + function server.save() + local doc = to_doc(server) + Db.save(doc) + server.id = doc.id + end + + function server.reload() + return Server.get_by_id(server.id) or error(server.id) + end + + function server.delete() + Db.run_in_transaction( function() + Db.delete("id:"..server.id) + end ) + end + + function server.write_img_html() + %><img icon src="https://cdn.discordapp.com/icons/<%=server.discord_id%>/<%=server.icon%>.png"><% + end + + function server.invite_url() + return "https://discord.gg/"..server.invite + end + + return server +end + +function Server.get_by_id(id) + local doc = Db.get_document("id:"..id) + return doc and from_doc(doc) +end + +local function search(query,sort,rows) + rows = rows or 1000000 + local docs = Db.search(query,1,rows,{sort=sort}) + local servers = {} + for _, doc in ipairs(docs) do + local server = from_doc(doc) + servers[#servers+1] = server + end + return servers +end + +function Server.get_user_servers() + return search( "server_owner_discord_id:"..get_user() ) +end + +return Server