view src/lib/Post.luan @ 8:be36282b556a

add new_thread
author Franklin Schmidt <fschmidt@gmail.com>
date Wed, 29 Jun 2022 00:04:09 -0600
parents
children 9674275019bb
line wrap: on
line source

local Luan = require "luan:Luan.luan"
local error = Luan.error
local set_metatable = Luan.set_metatable or error()
local Number = require "luan:Number.luan"
local long = Number.long or error()
local Time = require "luan:Time.luan"
local time_now = Time.now 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
		subject = doc.subject
		content = doc.content
		date = doc.date
		author_name = doc.post_author_name
		author_id = doc.post_author_id
		is_root = doc.post_is_root == "true"
		root_id = doc.post_root_id
	}
end

local function to_doc(post)
	return {
		type = "post"
		id = post.id
		subject = post.subject or error()
		content = post.content or error()
		date = post.date or time_now()
		post_author_name = post.author_name or error()
		post_author_id = long(post.author_id)
		post_is_root = post.is_root and "true" or nil
		post_root_id = post.root_id and long(post.root_id)
	}
end

local metatable = {}
function metatable.__index(post,key)
	if key == "author" then
		local User = require "site:/lib/User.luan"
		return User.get_by_id(post.author_id)
	end
	return nil
end

function Post.new(post)

	function post.save()
		local doc = to_doc(post)
		Db.save(doc)
		post.id = doc.id
	end

	set_metatable(post,metatable)
	return post
end

function Post.get_by_id(id)
	local doc = Db.get_document("id:"..id)
	return doc and Post.from_doc(doc)
end

function Post.new_thread(author,subject,content)
	return Db.run_in_transaction( function()
		local post = Post.new{
			subject = subject
			content = content
			author_name = author.name
			author_id = author.id
			is_root = true
		}
		post.save()
		post.root_id = post.id or error()
		post.save()
		return post
	end )
end

return Post