diff src/lib/Chat.luan @ 4:2da10ece826f

add Chat
author Franklin Schmidt <fschmidt@gmail.com>
date Sun, 27 Oct 2024 20:39:18 -0600
parents
children 41d35b72c774
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/lib/Chat.luan	Sun Oct 27 20:39:18 2024 -0600
@@ -0,0 +1,60 @@
+local Luan = require "luan:Luan.luan"
+local error = Luan.error
+local ipairs = Luan.ipairs or error()
+local Time = require "luan:Time.luan"
+local time_now = Time.now or error()
+local Db = require "site:/lib/Db.luan"
+local run_in_transaction = Db.run_in_transaction or error()
+
+
+local Chat = {}
+
+local function from_doc(doc)
+	doc.type == "chat" or error "wrong type"
+	return Chat.new {
+		id = doc.id
+		user_ids = doc.chat_user_ids
+		updated = doc.chat_updated
+	}
+end
+
+local function to_doc(chat)
+	return {
+		type = "chat"
+		id = chat.id
+		chat_user_ids = chat.user_ids or error()
+		chat_updated = chat.updated or error()
+	}
+end
+
+function Chat.new(chat)
+	chat.updated = chat.updated or time_now()
+
+	function chat.save()
+		local doc = to_doc(chat)
+		Db.save(doc)
+		chat.id = doc.id
+	end
+
+	function chat.delete()
+		run_in_transaction( function()
+			local id = chat.id
+			-- Db.delete("chat_user_ids:"..id)
+			Db.delete("id:"..id)
+		end )
+	end
+
+	return chat
+end
+
+function Chat.search(query,sort,rows)
+	rows = rows or 1000000
+	local chats = {}
+	local docs = Db.search(query,1,rows,{sort=sort})
+	for _, doc in ipairs(docs) do
+		chats[#chats+1] = from_doc(doc)
+	end
+	return chats
+end
+
+return Chat