Mercurial Hosting > luan
comparison examples/blog/src/lib/Post.luan @ 1220:4721c482c86b
cleaner Db example
| author | Franklin Schmidt <fschmidt@gmail.com> |
|---|---|
| date | Wed, 21 Mar 2018 15:54:57 -0600 |
| parents | 1f9d34a6f308 |
| children | 709f7498a363 |
comparison
equal
deleted
inserted
replaced
| 1219:b602badc876b | 1220:4721c482c86b |
|---|---|
| 4 local type = Luan.type or error() | 4 local type = Luan.type or error() |
| 5 local Time = require "luan:Time.luan" | 5 local Time = require "luan:Time.luan" |
| 6 local now = Time.now or error() | 6 local now = Time.now or error() |
| 7 local String = require "luan:String.luan" | 7 local String = require "luan:String.luan" |
| 8 local trim = String.trim or error() | 8 local trim = String.trim or error() |
| 9 local Db = require "site:/lib/Db.luan" | 9 local db = require("site:/lib/Db.luan").db or error() |
| 10 | 10 |
| 11 | 11 |
| 12 local Post = {} | 12 local Post = {} |
| 13 | 13 |
| 14 local function from_doc(doc) | 14 local function from_doc(doc) |
| 31 id = this.id | 31 id = this.id |
| 32 subject = this.subject | 32 subject = this.subject |
| 33 content = this.content | 33 content = this.content |
| 34 date = this.date | 34 date = this.date |
| 35 } | 35 } |
| 36 Db.save(doc) | 36 db.save(doc) |
| 37 this.id = doc.id | 37 this.id = doc.id |
| 38 end | 38 end |
| 39 | 39 |
| 40 return this | 40 return this |
| 41 end | 41 end |
| 42 | 42 |
| 43 function Post.get_by_id(id) | 43 function Post.get_by_id(id) |
| 44 local doc = Db.get_document("id:"..id) | 44 local doc = db.get_document("id:"..id) |
| 45 return doc and from_doc(doc) | 45 return doc and from_doc(doc) |
| 46 end | 46 end |
| 47 | 47 |
| 48 function Post.get_all() | 48 function Post.get_all() |
| 49 local docs = Db.search("type:post",1,1000,"id desc") | 49 local docs = db.search("type:post",1,1000,"id desc") |
| 50 local posts = {} | 50 local posts = {} |
| 51 for _, doc in ipairs(docs) do | 51 for _, doc in ipairs(docs) do |
| 52 posts[#posts+1] = from_doc(doc) | 52 posts[#posts+1] = from_doc(doc) |
| 53 end | 53 end |
| 54 return posts | 54 return posts |
| 57 function Post.search(query) | 57 function Post.search(query) |
| 58 query = trim(query) | 58 query = trim(query) |
| 59 if #query == 0 then | 59 if #query == 0 then |
| 60 return Post.get_all() | 60 return Post.get_all() |
| 61 end | 61 end |
| 62 local docs = Db.search(query,1,1000) | 62 local docs = db.search(query,1,1000) |
| 63 local posts = {} | 63 local posts = {} |
| 64 for _, doc in ipairs(docs) do | 64 for _, doc in ipairs(docs) do |
| 65 posts[#posts+1] = from_doc(doc) | 65 posts[#posts+1] = from_doc(doc) |
| 66 end | 66 end |
| 67 return posts | 67 return posts |
