diff src/lib/Post.luan @ 10:f9e6a4cc4f7d

add Post
author Franklin Schmidt <fschmidt@gmail.com>
date Wed, 30 Oct 2024 23:18:45 -0600
parents
children c54c806fcc6e
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/lib/Post.luan	Wed Oct 30 23:18:45 2024 -0600
@@ -0,0 +1,53 @@
+local Luan = require "luan:Luan.luan"
+local error = Luan.error
+local ipairs = Luan.ipairs or error()
+local Number = require "luan:Number.luan"
+local long = Number.long or error()
+local Db = require "site:/lib/Db.luan"
+
+
+local Post = {}
+
+local function from_doc(doc)
+	doc.type == "post" or error "wrong type"
+	return Post.new {
+		id = doc.id
+		chat_id = doc.post_chat_id
+		author_id = doc.author_id
+		date = doc.date
+		content = doc.content
+	}
+end
+
+local function to_doc(post)
+	return {
+		type = "post"
+		id = post.id
+		post_chat_id = long(post.chat_id)
+		author_id = long(post.author_id)
+		date = long(post.date)
+		content = post.content or error()
+	}
+end
+
+function Post.new(post)
+	function post.save()
+		local doc = to_doc(post)
+		Db.save(doc)
+		post.id = doc.id
+	end
+
+	return post
+end
+
+function Post.search(query,sort,rows)
+	rows = rows or 1000000
+	local posts = {}
+	local docs = Db.search(query,1,rows,{sort=sort})
+	for _, doc in ipairs(docs) do
+		posts[#posts+1] = from_doc(doc)
+	end
+	return posts
+end
+
+return Post