地平线之旅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.jianshu.com/p/8406baeb01c5
[2] http://horizon.io/docs/getting-started/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 229,885评论 6 541
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 99,312评论 3 429
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 177,993评论 0 383
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 63,667评论 1 317
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 72,410评论 6 411
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 55,778评论 1 328
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 43,775评论 3 446
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 42,955评论 0 289
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 49,521评论 1 335
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 41,266评论 3 358
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 43,468评论 1 374
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 38,998评论 5 363
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,696评论 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 35,095评论 0 28
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 36,385评论 1 294
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 52,193评论 3 398
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 48,431评论 2 378

推荐阅读更多精彩内容

  • Horizon使用JSON Web Tokens实现用户的认证,不管你是不是使用Horizon进行开发,你都应该了...
    时见疏星阅读 673评论 1 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,819评论 18 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,714评论 25 708
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,914评论 6 342
  • 你走在前面 我看不见你 你转过身来 却仍难触及 我们之间没有几亿光年的距离 只是这浓尘雾霭里 你看不见我 我看不见...
    小北东南西西西阅读 288评论 0 1