之前的文章我們介紹了Horizon,無需編寫后端代碼,就能構建實時應用,今天我們繼續我們的地平線之旅!
安裝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
: 運行服務端
創建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
我們看一下項目結構:
$ tree example_app
example_app/
├── .hz
│ └── config.toml
├── dist
│ └── index.html
└── src
-
dist
里面是靜態文件。 -
src
使你構建系統的源文件。 -
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的數據庫,我們可以通過不同的端口來訪問后臺。
--dev
這個標簽代表了下面這些設置:
- 自動運行RethinkDB (
--start-rethinkdb
) - 以非安全模式運行,不要求SSL/TLS (
--secure no
) - 關閉了權限系統 (--permissions no)
- 表和索引如果不存在被自動創建 (
--auto-create-collection
and--auto-create-index
) - 靜態文件將在
dist
文件夾被serve (--serve-static ./dist
)
如果不使用--dev
標簽,在生產環境里,你需要使用配置文件.hz/config.toml
來設置這些參數。
連接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
是一個事件處理器,它再客戶端成功連接到服務端的時候被執行。我們的連接僅僅在<h1>
標簽中添加了"App works!"
。它只是檢測了Horizon是否工作,還并沒有用到RethinkDB。
Horizon集合
Horizon的核心是集合(Collection對象),使你能夠獲取、存儲和篩選文檔記錄。許多集合方法讀寫文檔返回的是RxJS Observables。關于Rx的一些基本只是可以看RXJS 介紹
// 創建一個"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方法來獲取集合中的條目,并且提供了一個錯誤處理器。
刪除數據
刪除集合中的條目,我們可以使用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])
你可以級聯subscribe
函數到remove
函數后面,來獲取響應和錯誤處理器。
觀察變化
我們可以使用watch來監聽整個集合、查詢或者單個條目。這讓我們能夠隨著數據庫數據的變化立即變更應用狀態。
// 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會接收整個文檔集合當有一個條目發生變化。這使得Vue或React這類框架很容易集成,它允許你使用Horizon新返回的數組替換現有的集合拷貝。
我們來看一下示例:
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。
結合所有
現在我們結合上述知識點,構建一個聊天應用,消息以倒序呈現:
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與現有應用結合
Horizon有兩種方式與現有應用結合:
- 使用Horizon服務器提供的
horizon.js
- 添加
@horizon/client
的依賴
這里推薦的是第一種做法,因為它將預防任何潛在的client和Horizon server的版本沖突。當然,如果你使用Webpack或其他相似的構建工具,可以將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.lxweimin.com/p/8406baeb01c5
[2] http://horizon.io/docs/getting-started/