前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >地平线之旅 — Horizon初探

地平线之旅 — Horizon初探

作者头像
时见疏星
发布2018-06-01 11:43:42
5530
发布2018-06-01 11:43:42
举报
文章被收录于专栏:星流全栈星流全栈

之前的文章我们介绍了Horizon,无需编写后端代码,就能构建实时应用,今天我们继续我们的地平线之旅!点击「阅读原文」查看完整文章哦!

安装RethinkDB

使用Horizon首先需要安装RethinkDB,并且版本在2.3.1之上,这里我们以OSX为例使用homebrew安装:

代码语言:javascript
复制
brew updatebrew install rethinkdb

如果之前安装过老版本的rethinkdb,可以使用brew upgrade rethinkdb来更新。目前最新版本为2.3.3。

安装Horizon CLI

首先我们安装Horizon CLI,它提供了hz命令:

代码语言:javascript
复制
npm install -g horizon

这里我们用到Horizon的命令行工具提供的两个指令:

代码语言:javascript
复制
init [directory]: 初始化一个Horizon应用
serve: 运行服务端

创建Horizon项目

代码语言:javascript
复制
$ 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

我们看一下项目结构:

代码语言:javascript
复制
$ 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来启动服务器。

代码语言:javascript
复制
App available at http://127.0.0.1:8181RethinkDB
   ├── Admin interface: http://localhost:52936
   └── Drivers can connect to port 52935

Starting Horizon...

可以看到,增加了--dev后,不仅启动了服务器,还有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

代码语言:javascript
复制
<!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 介绍

代码语言:javascript
复制
// 创建一个"messages"集合

const chat = horizon("messages");

使用store方法存储

代码语言:javascript
复制
let message = {
  text: "What a beautiful horizon!",
  datetime: new Date(),
  author: "@dalanmiller"}

chat.store(message);

使用fetch方法读取

代码语言:javascript
复制
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

代码语言:javascript
复制
// 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来监听整个集合、查询或者单个条目。这让我们能够随着数据库数据的变化立即变更应用状态。

代码语言:javascript
复制
// 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新返回的数组替换现有的集合拷贝。

我们来看一下示例:

代码语言:javascript
复制
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

结合所有

现在我们结合上述知识点,构建一个聊天应用,消息以倒序呈现:

代码语言:javascript
复制
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 itemconst 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),
)

你也可以获取客户端与服务端是否连接的通知:

代码语言:javascript
复制
// 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 )。

代码语言:javascript
复制
<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.jianshu.com/p/8406baeb01c5 [2] http://horizon.io/docs/getting-started/

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2016-06-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 星流全栈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 安装RethinkDB
  • 安装Horizon CLI
  • 创建Horizon项目
  • 启动Horizon服务器
  • 连接Horizon
  • Horizon集合
  • 删除数据
  • 观察变化
  • 结合所有
  • Horizon与现有应用结合
  • 参考
相关产品与服务
命令行工具
腾讯云命令行工具 TCCLI 是管理腾讯云资源的统一工具。使用腾讯云命令行工具,您可以快速调用腾讯云 API 来管理您的腾讯云资源。此外,您还可以基于腾讯云的命令行工具来做自动化和脚本处理,以更多样的方式进行组合和重用。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档