实时API

服务 一章中, 我们看到Feathers服务在 create 时自动发送 created, updated, patchchedremoved 事件, update, patchremove 服务方法返回. 实时意味着这些事件也会发布到连接的客户端, 以便他们可以做出相应的反应, 例如, 更新他们的UI.

为了实现与客户的实时通信, 我们需要一种支持双向通信的传输. 在Feathers中, 这些是 Socket.ioPrimus transport 都使用 websockets 用于接收实时事件*以及*调用服务方法.

重要

REST APIs 不支持实时更新. 由于套接字传输也允许调用服务方法并且通常性能更好, 因此我们建议尽可能使用实时传输.

在本章中, 我们将使用Socket.io并创建一个 数据库 实时API, 它仍然支持 REST APIs.

使用传输

安装后

npm install @feathersjs/socketio --save

可以配置Socket.io传输并使用这样的标准配置:

const feathers = require('@feathersjs/feathers');
const socketio = require('@feathersjs/socketio');

// Create a Feathers application
const app = feathers();

// Configure the Socket.io transport
app.configure(socketio());

// Start the server on port 3030
app.listen(3030);

它还与REST API设置结合使用:

const feathers = require('@feathersjs/feathers');
const express = require('@feathersjs/express');
const socketio = require('@feathersjs/socketio');

// This creates an app that is both, an Express and Feathers app
const app = express(feathers());

// Turn on JSON body parsing for REST services
app.use(express.json())
// Turn on URL-encoded body parsing for REST services
app.use(express.urlencoded({ extended: true }));
// Set up REST transport using Express
app.configure(express.rest());
// Configure the Socket.io transport
app.configure(socketio());
// Set up an error handler that gives us nicer errors
app.use(express.errorHandler());


// Start the server on port 3030
app.listen(3030);

通道

通道确定应将哪些实时事件发送到哪个客户端. 例如, 我们可能只想向同一房间中经过身份验证的用户或用户发送消息. 但是, 对于此示例, 我们将仅为所有连接启用实时功能:

// On any real-time connection, add it to the `everybody` channel
app.on('connection', connection => app.channel('everybody').join(connection));

// Publish all events to the `everybody` channel
app.publish(() => app.channel('everybody'));

注解

有关频道的更多信息, 请参阅 事件频道.

消息API

总而言之, 我们的REST和带有消息服务 app.js 的实时API看起来像这样:

const feathers = require('@feathersjs/feathers');
const express = require('@feathersjs/express');
const socketio = require('@feathersjs/socketio');
const memory = require('feathers-memory');

// This creates an app that is both, an Express and Feathers app
const app = express(feathers());

// Turn on JSON body parsing for REST services
app.use(express.json())
// Turn on URL-encoded body parsing for REST services
app.use(express.urlencoded({ extended: true }));
// Set up REST transport using Express
app.configure(express.rest());

// Configure the Socket.io transport
app.configure(socketio());

// On any real-time connection, add it to the `everybody` channel
app.on('connection', connection => app.channel('everybody').join(connection));

// Publish all events to the `everybody` channel
app.publish(() => app.channel('everybody'));

// Initialize the messages service
app.use('messages', memory({
  paginate: {
    default: 10,
    max: 25
  }
}));

// Set up an error handler that gives us nicer errors
app.use(express.errorHandler());

// Start the server on port 3030
const server = app.listen(3030);

server.on('listening', () => console.log('Feathers API started at localhost:3030'));

与往常一样, 我们可以通过运行再次启动我们的服务器

node app.js

使用API

可以通过建立websocket连接来使用实时API. 为此我们需要Socket.io客户端, 我们可以通过更新 public/index.html 来包含它:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Feathers Basics</title>
</head>
<body>
  <h1>Welcome to Feathers</h1>
  <p>Open up the console in your browser.</p>
  <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
  <script type="text/javascript" src="//unpkg.com/@feathersjs/client@^3.0.0/dist/feathers.js"></script>
  <script type="text/javascript" src="//unpkg.com/feathers-memory@^2.0.0/dist/feathers-memory.js"></script>
  <script src="client.js"></script>
</body>
</html>

然后我们可以通过将 public/client.js 更新为此来初始化并使用套接字直接进行一些调用并监听实时事件:

/* global io */

// Create a websocket connecting to our Feathers server
const socket = io('http://localhost:3030');

// Listen to new messages being created
socket.on('messages created', message =>
  console.log('Someone created a message', message)
);

socket.emit('create', 'messages', {
  text: 'Hello from socket'
}, (error, result) => {
  if (error) throw error
  socket.emit('find', 'messages', (error, messageList) => {
    if (error) throw error
    console.log('Current messages', messageList);
  });
});

下一步是什么?

在本章中, 我们添加了Socket.io传输, 并了解了如何使用通道将事件从服务器发送到客户端. 在 客户端使用 中, 我们将了解如何使用浏览器Feathers应用程序和客户端服务轻松处理这些事件.