view src/lib/Chat.luan @ 11:563a5358f2ee

add delete_chat
author Franklin Schmidt <fschmidt@gmail.com>
date Thu, 31 Oct 2024 19:17:53 -0600
parents 41d35b72c774
children 9f45d32670ae
line wrap: on
line source

local Luan = require "luan:Luan.luan"
local error = Luan.error
local ipairs = Luan.ipairs or error()
local Table = require "luan:Table.luan"
local concat = Table.concat or error()
local is_empty = Table.is_empty 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("post_chat_id:"..id)
			Db.delete("id:"..id)
		end )
	end

	function chat.other_users_email(user)
		local User = require "site:/lib/User.luan"
		local get_user_by_id = User.get_by_id or error()

		local my_id = user.id
		local t = {}
		for _, user_id in ipairs(chat.user_ids) do
			if user_id ~= my_id then
				local other_user = get_user_by_id(user_id) or error()
				t[#t+1] = other_user.email
			end
		end
		return concat( t, ", " )
	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

function Chat.get_by_id(id)
	local doc = Db.get_document("id:"..id)
	return doc and doc.type=="chat" and from_doc(doc) or nil
end

return Chat