comparison 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
comparison
equal deleted inserted replaced
7:0472897e790d 8:be36282b556a
1 local Luan = require "luan:Luan.luan"
2 local error = Luan.error
3 local set_metatable = Luan.set_metatable or error()
4 local Number = require "luan:Number.luan"
5 local long = Number.long or error()
6 local Time = require "luan:Time.luan"
7 local time_now = Time.now or error()
8 local Db = require "site:/lib/Db.luan"
9
10
11 local Post = {}
12
13 local function from_doc(doc)
14 doc.type == "post" or error "wrong type"
15 return Post.new {
16 id = doc.id
17 subject = doc.subject
18 content = doc.content
19 date = doc.date
20 author_name = doc.post_author_name
21 author_id = doc.post_author_id
22 is_root = doc.post_is_root == "true"
23 root_id = doc.post_root_id
24 }
25 end
26
27 local function to_doc(post)
28 return {
29 type = "post"
30 id = post.id
31 subject = post.subject or error()
32 content = post.content or error()
33 date = post.date or time_now()
34 post_author_name = post.author_name or error()
35 post_author_id = long(post.author_id)
36 post_is_root = post.is_root and "true" or nil
37 post_root_id = post.root_id and long(post.root_id)
38 }
39 end
40
41 local metatable = {}
42 function metatable.__index(post,key)
43 if key == "author" then
44 local User = require "site:/lib/User.luan"
45 return User.get_by_id(post.author_id)
46 end
47 return nil
48 end
49
50 function Post.new(post)
51
52 function post.save()
53 local doc = to_doc(post)
54 Db.save(doc)
55 post.id = doc.id
56 end
57
58 set_metatable(post,metatable)
59 return post
60 end
61
62 function Post.get_by_id(id)
63 local doc = Db.get_document("id:"..id)
64 return doc and Post.from_doc(doc)
65 end
66
67 function Post.new_thread(author,subject,content)
68 return Db.run_in_transaction( function()
69 local post = Post.new{
70 subject = subject
71 content = content
72 author_name = author.name
73 author_id = author.id
74 is_root = true
75 }
76 post.save()
77 post.root_id = post.id or error()
78 post.save()
79 return post
80 end )
81 end
82
83 return Post