UNPKG

2.48 kBMarkdownView Raw
1WebSockets in Ravel have been implemented in an extremely minimalistic fashion, both in keeping with Ravel's philosophy of minimizing dependencies, and to promote safer usage of WebSocket technology within applications.
2
3WebSockets in Ravel:
4- Support a basic publish/subscribe model
5- Wrap around [ws](https://github.com/websockets/ws), rather than a more complex (and dependency-heavy) library with transport fallbacks.
6- Are automatically safe for horizontal scaling, using `redis` to synchronize between different replicas of your application.
7- Are essentially **one-way**. Browser clients receive messages, but make HTTP requests to "send" them. This allows you to 1. set the rules for who can publish what and when, and 2. leverage existing Ravel functionality like `@authenticated` when defining your own publish endpoints. This also avoids the introduction of a custom message protocol such as STOMP and keeps things as straightforward as possible.
8
9To utilize WebSockets, inject `$ws` into any `Module`, `Resource` or `Routes` class, and define your own endpoints (and/or logic) which allow clients to subscribe to topics, for example:
10
11```js
12/**
13 * A RESTful resource to manage subscriptions
14 *
15 * You could protect any of these endpoints with @authenticated,
16 * or define your own custom application logic!
17 */
18@Ravel.Resource('/ws/mytopic/subscription')
19@Ravel.autoinject('$ws')
20class WSSubscriptions {
21 // user would send an empty POST to /ws/mytopic/subscription
22 // to subscribe to my.topic
23 async post (ctx) {
24 ctx.body = await this.$ws.subscribe('my.topic', ctx);
25 }
26
27 // user would send an empty DELETE to /ws/mytopic/subscription
28 // to unsubscribe from my.topic
29 async deleteAll (ctx) {
30 ctx.body = await this.$ws.unsubscribe('my.topic', ctx);
31 }
32}
33```
34
35```js
36/**
37 * A RESTful resource to handle message publication
38 */
39@Ravel.Resource('/ws/mytopic')
40@Ravel.inject('koa-bodyparser')
41@Ravel.autoinject('$ws')
42class WSMessages {
43 constructor(bodyparser) {
44 this['body-parser'] = bodyparser();
45 }
46 // user would send a POST to /ws/mytopic
47 // to send a message
48 @Ravel.Resource.before('bodyparser')
49 async post (ctx) {
50 ctx.body = await this.$ws.publish('my.topic', ctx.request.body);
51 }
52}
53```
54
55Then, on the client, the [ws](https://github.com/websockets/ws) library can be used normally to connect to the Ravel server and listen for the `on('message')` event.
56
57WebSockets can be disabled via `app.set('enable websockets', false)`.