地平線之旅01 — Horizon初探

Horizon

之前的文章我們介紹了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的數據庫,我們可以通過不同的端口來訪問后臺。

RethinkDB 后臺

--dev這個標簽代表了下面這些設置:

  1. 自動運行RethinkDB (--start-rethinkdb)
  2. 以非安全模式運行,不要求SSL/TLS (--secure no)
  3. 關閉了權限系統 (--permissions no)
  4. 表和索引如果不存在被自動創建 (--auto-create-collection
    and --auto-create-index)
  5. 靜態文件將在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。

Example App

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方法來獲取集合中的條目,并且提供了一個錯誤處理器。

刪除數據

刪除集合中的條目,我們可以使用removeremoveAll

// 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會接收整個文檔集合當有一個條目發生變化。這使得VueReact這類框架很容易集成,它允許你使用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有兩種方式與現有應用結合:

  1. 使用Horizon服務器提供的horizon.js
  2. 添加@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/

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Horizon使用JSON Web Tokens實現用戶的認證,不管你是不是使用Horizon進行開發,你都應該了...
    時見疏星閱讀 714評論 1 0
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,981評論 19 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,476評論 25 708
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,970評論 6 342
  • 你走在前面 我看不見你 你轉過身來 卻仍難觸及 我們之間沒有幾億光年的距離 只是這濃塵霧靄里 你看不見我 我看不見...
    小北東南西西西閱讀 290評論 0 1