之前的文章我們介紹了Horizon例获,無需編寫后端代碼闪彼,就能構(gòu)建實時應用壳快,今天我們繼續(xù)我們的地平線之旅洼专!
安裝RethinkDB
使用Horizon首先需要安裝RethinkDB,并且版本在2.3.1之上者祖,這里我們以OSX為例使用homebrew安裝:
brew update
brew install rethinkdb
如果之前安裝過老版本的rethinkdb立莉,可以使用brew upgrade rethinkdb
來更新。目前最新版本為2.3.3七问。
安裝Horizon CLI
首先我們安裝Horizon CLI蜓耻,它提供了hz
命令:
npm install -g horizon
這里我們用到Horizon的命令行工具提供的兩個指令:
-
init [directory]
: 初始化一個Horizon應用 -
serve
: 運行服務端
創(chuàng)建Horizon項目
$ hz init example_app
Created new project directory example_app
Created example_app/src directory
Created example_app/dist directory
Created example_app/dist/index.html example
Created example_app/.hz directory
Created example_app/.hz/config.toml
我們看一下項目結(jié)構(gòu):
$ tree example_app
example_app/
├── .hz
│ └── config.toml
├── dist
│ └── index.html
└── src
-
dist
里面是靜態(tài)文件。 -
src
使你構(gòu)建系統(tǒng)的源文件械巡。 -
dist/index.html
是示例文件刹淌。 -
.hz/config.toml
是一個toml配置文件。
啟動Horizon服務器
我們可以使用hz serve --dev
來啟動服務器讥耗。
App available at http://127.0.0.1:8181
RethinkDB
├── Admin interface: http://localhost:52936
└── Drivers can connect to port 52935
Starting Horizon...
可以看到有勾,增加了--dev
后,不僅啟動了服務器葛账,還有RethinkDB的數(shù)據(jù)庫柠衅,我們可以通過不同的端口來訪問后臺皮仁。
--dev
這個標簽代表了下面這些設置:
- 自動運行RethinkDB (
--start-rethinkdb
) - 以非安全模式運行籍琳,不要求SSL/TLS (
--secure no
) - 關閉了權限系統(tǒng) (--permissions no)
- 表和索引如果不存在被自動創(chuàng)建 (
--auto-create-collection
and--auto-create-index
) - 靜態(tài)文件將在
dist
文件夾被serve (--serve-static ./dist
)
如果不使用--dev
標簽,在生產(chǎn)環(huán)境里贷祈,你需要使用配置文件.hz/config.toml
來設置這些參數(shù)趋急。
連接Horizon
我們來看一下index.html
:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="/horizon/horizon.js"></script>
<script>
var horizon = Horizon();
horizon.onReady(function() {
document.querySelector('h1').innerHTML = 'App works!'
});
horizon.connect();
</script>
</head>
<body>
<marquee><h1></h1></marquee>
</body>
</html>
var horizon = Horizon()
初始化了Horizon對象,它只有一些方法势誊,包括連接相關的事件和實例化Horizon的集合呜达。
onReady
是一個事件處理器,它再客戶端成功連接到服務端的時候被執(zhí)行粟耻。我們的連接僅僅在<h1>
標簽中添加了"App works!"
查近。它只是檢測了Horizon是否工作眉踱,還并沒有用到RethinkDB。
Horizon集合
Horizon的核心是集合(Collection對象)霜威,使你能夠獲取谈喳、存儲和篩選文檔記錄。許多集合方法讀寫文檔返回的是RxJS Observables戈泼。關于Rx的一些基本只是可以看RXJS 介紹
// 創(chuàng)建一個"messages"集合
const chat = horizon("messages");
使用store方法存儲
let message = {
text: "What a beautiful horizon!",
datetime: new Date(),
author: "@dalanmiller"
}
chat.store(message);
使用fetch方法讀取
chat.fetch().subscribe(
(items) => {
items.forEach((item) => {
// Each result from the chat collection
// will pass through this function
console.log(item);
})
},
// If an error occurs, this function
// will execute with the `err` message
(err) => {
console.log(err);
})
這里使用了RxJS的subscribe方法來獲取集合中的條目婿禽,并且提供了一個錯誤處理器。
刪除數(shù)據(jù)
刪除集合中的條目大猛,我們可以使用remove或removeAll
// These two queries are equivalent and will remove the document with id: 1
chat.remove(1).subscribe((id) => { console.log(id) })
chat.remove({id: 1}).subscribe((id) => {console.log(id)})
// Will remove documents with ids 1, 2, and 3 from the collection
chat.removeAll([1, 2, 3])
你可以級聯(lián)subscribe
函數(shù)到remove
函數(shù)后面扭倾,來獲取響應和錯誤處理器。
觀察變化
我們可以使用watch來監(jiān)聽整個集合挽绩、查詢或者單個條目膛壹。這讓我們能夠隨著數(shù)據(jù)庫數(shù)據(jù)的變化立即變更應用狀態(tài)。
// Watch all documents. If any of them change, call the handler function.
chat.watch().subscribe((docs) => { console.log(docs) })
// Query all documents and sort them in ascending order by datetime,
// then if any of them change, the handler function is called.
chat.order("datetime").watch().subscribe((docs) => { console.log(docs) })
// Watch a single document in the collection.
chat.find({author: "@dalanmiller"}).watch().subscribe((doc) => { console.log(doc) })
默認情況下唉堪,watch
返回的Observable會接收整個文檔集合當有一個條目發(fā)生變化恢筝。這使得Vue或React這類框架很容易集成,它允許你使用Horizon新返回的數(shù)組替換現(xiàn)有的集合拷貝巨坊。
我們來看一下示例:
let chats = [];
// Query chats with `.order`, which by default is in ascending order
chat.order("datetime").watch().subscribe(
// Returns the entire array
(newChats) => {
// Here we replace the old value of `chats` with the new
// array. Frameworks such as React will re-render based
// on the new values inserted into the array.
chats = newChats;
},
(err) => {
console.log(err);
})
更多Horizon+React示例可以參見complete Horizon & React example撬槽。
結(jié)合所有
現(xiàn)在我們結(jié)合上述知識點,構(gòu)建一個聊天應用趾撵,消息以倒序呈現(xiàn):
let chats = [];
// Retrieve all messages from the server
const retrieveMessages = () => {
chat.order('datetime')
// fetch all results as an array
.fetch()
// Retrieval successful, update our model
.subscribe((newChats) => {
chats = chats.concat(newChats);
},
// Error handler
error => console.log(error),
// onCompleted handler
() => console.log('All results received!')
)
};
// Retrieve an single item by id
const retrieveMessage = id => {
chat.find(id).fetch()
// Retrieval successful
.subscribe(result => {
chats.push(result);
},
// Error occurred
error => console.log(error))
};
// Store new item
const storeMessage = (message) => {
chat.store(message)
.subscribe(
// Returns id of saved objects
result => console.log(result),
// Returns server error message
error => console.log(error)
)
};
// Replace item that has equal `id` field
// or insert if it doesn't exist.
const updateMessage = message => {
chat.replace(message);
};
// Remove item from collection
const deleteMessage = message => {
chat.remove(message);
};
chat.watch().subscribe(chats => {
renderChats(allChats)
},
// When error occurs on server
error => console.log(error),
)
你也可以獲取客戶端與服務端是否連接的通知:
// Triggers when client successfully connects to server
horizon.onReady().subscribe(() => console.log("Connected to Horizon server"))
// Triggers when disconnected from server
horizon.onDisconnected().subscribe(() => console.log("Disconnected from Horizon server"))
在這里侄柔,你編寫了一個實時聊天應用,而且不用書寫一行后端代碼占调。
Horizon與現(xiàn)有應用結(jié)合
Horizon有兩種方式與現(xiàn)有應用結(jié)合:
- 使用Horizon服務器提供的
horizon.js
- 添加
@horizon/client
的依賴
這里推薦的是第一種做法暂题,因為它將預防任何潛在的client和Horizon server的版本沖突。當然究珊,如果你使用Webpack或其他相似的構(gòu)建工具薪者,可以將client庫作為NPM依賴(npm install @horizon/client
)。
<script src="localhost:8181/horizon/horizon.js"></script>
// Specify the host property for initializing the Horizon connection
const horizon = Horizon({host: 'localhost:8181'});
參考
[1] http://www.reibang.com/p/8406baeb01c5
[2] http://horizon.io/docs/getting-started/