Mercurial Hosting > luan
comparison examples/blog/src/lib/Post.luan @ 779:c38f6619feb9
move blog into examples
| author | Franklin Schmidt <fschmidt@gmail.com> |
|---|---|
| date | Sun, 28 Aug 2016 14:50:47 -0600 |
| parents | blog/src/lib/Post.luan@ca169567ce07 |
| children | bae2d0c2576c |
comparison
equal
deleted
inserted
replaced
| 778:305ffb00ebc1 | 779:c38f6619feb9 |
|---|---|
| 1 local Luan = require "luan:Luan.luan" | |
| 2 local error = Luan.error | |
| 3 local ipairs = Luan.ipairs or error() | |
| 4 local assert_string = Luan.assert_string or error() | |
| 5 local Time = require "luan:Time.luan" | |
| 6 local now = Time.now or error() | |
| 7 local String = require "luan:String.luan" | |
| 8 local trim = String.trim or error() | |
| 9 local Db = require "site:/lib/Db.luan" | |
| 10 | |
| 11 | |
| 12 local M = {} | |
| 13 | |
| 14 local function from_doc(doc) | |
| 15 return M.new { | |
| 16 id = doc.id | |
| 17 subject = doc.subject | |
| 18 content = doc.content | |
| 19 date = doc.date | |
| 20 } | |
| 21 end | |
| 22 | |
| 23 function M.new(this) | |
| 24 assert_string(this.subject) | |
| 25 assert_string(this.content) | |
| 26 this.date = this.date or now() | |
| 27 | |
| 28 function this.save() | |
| 29 local doc = { | |
| 30 type = "post" | |
| 31 id = this.id | |
| 32 subject = this.subject | |
| 33 content = this.content | |
| 34 date = this.date | |
| 35 } | |
| 36 Db.save(doc) | |
| 37 this.id = doc.id | |
| 38 end | |
| 39 | |
| 40 return this | |
| 41 end | |
| 42 | |
| 43 function M.get_by_id(id) | |
| 44 local doc = Db.get_document("id:"..id) | |
| 45 return doc and from_doc(doc) | |
| 46 end | |
| 47 | |
| 48 function M.get_all() | |
| 49 local docs = Db.search("type:post",1,1000,"id desc") | |
| 50 local posts = {} | |
| 51 for _, doc in ipairs(docs) do | |
| 52 posts[#posts+1] = from_doc(doc) | |
| 53 end | |
| 54 return posts | |
| 55 end | |
| 56 | |
| 57 function M.search(query) | |
| 58 query = trim(query) | |
| 59 if #query == 0 then | |
| 60 return M.get_all() | |
| 61 end | |
| 62 local docs = Db.search(query,1,1000) | |
| 63 local posts = {} | |
| 64 for _, doc in ipairs(docs) do | |
| 65 posts[#posts+1] = from_doc(doc) | |
| 66 end | |
| 67 return posts | |
| 68 end | |
| 69 | |
| 70 return M |
