diff 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
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/blog/src/lib/Post.luan	Sun Aug 28 14:50:47 2016 -0600
@@ -0,0 +1,70 @@
+local Luan = require "luan:Luan.luan"
+local error = Luan.error
+local ipairs = Luan.ipairs or error()
+local assert_string = Luan.assert_string or error()
+local Time = require "luan:Time.luan"
+local now = Time.now or error()
+local String = require "luan:String.luan"
+local trim = String.trim or error()
+local Db = require "site:/lib/Db.luan"
+
+
+local M = {}
+
+local function from_doc(doc)
+	return M.new {
+		id = doc.id
+		subject = doc.subject
+		content = doc.content
+		date = doc.date
+	}
+end
+
+function M.new(this)
+	assert_string(this.subject)
+	assert_string(this.content)
+	this.date = this.date or now()
+
+	function this.save()
+		local doc = {
+			type = "post"
+			id = this.id
+			subject = this.subject
+			content = this.content
+			date = this.date
+		}
+		Db.save(doc)
+		this.id = doc.id
+	end
+
+	return this
+end
+
+function M.get_by_id(id)
+	local doc = Db.get_document("id:"..id)
+	return doc and from_doc(doc)
+end
+
+function M.get_all()
+	local docs = Db.search("type:post",1,1000,"id desc")
+	local posts = {}
+	for _, doc in ipairs(docs) do
+		posts[#posts+1] = from_doc(doc)
+	end
+	return posts
+end
+
+function M.search(query)
+	query = trim(query)
+	if #query == 0 then
+		return M.get_all()
+	end
+	local docs = Db.search(query,1,1000)
+	local posts = {}
+	for _, doc in ipairs(docs) do
+		posts[#posts+1] = from_doc(doc)
+	end
+	return posts
+end
+
+return M