From fb33a992818718b6b8a7ee9598237837d961830d Mon Sep 17 00:00:00 2001 From: thosakwe Date: Sat, 17 Sep 2016 16:00:17 -0400 Subject: [PATCH] No controllers yet --- README.md | 12 +++++++++++- lib/browser.dart | 3 ++- lib/server.dart | 11 +++++++++-- test/common.dart | 2 +- 4 files changed, 23 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 015720eb..af853612 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,13 @@ # angel_websocket -WebSocket plugin for Angel. Features JWT support. +WebSocket plugin for Angel. + +This plugin broadcasts events from hooked services via WebSockets. + +In addition, +it adds itself to the app's IoC container as `AngelWebSocket`, so that it can be used +in controllers as well. + +WebSocket contexts are add to `req.params` as `'socket'`. # Usage @@ -51,6 +59,8 @@ class Car extends srv.Model { main() async { Angel app = new WebSocketClient("/ws"); + // Wait for WebSocket connection... + await app.connect(); var Cars = app.service("api/cars", type: Car); Cars.onCreated.listen((e) { diff --git a/lib/browser.dart b/lib/browser.dart index 5e208a92..70c64bcc 100644 --- a/lib/browser.dart +++ b/lib/browser.dart @@ -12,6 +12,7 @@ class WebSocketClient extends Angel { WebSocketClient(String wsEndpoint) : super(wsEndpoint) { _socket = new WebSocket(wsEndpoint); + _connect(); } onData(data) { @@ -60,7 +61,7 @@ class WebSocketClient extends Angel { } } - Future connect() async { + void _connect() { _socket.onMessage.listen((MessageEvent event) { onData(event.data); }); diff --git a/lib/server.dart b/lib/server.dart index ad2e3559..5a42b98b 100644 --- a/lib/server.dart +++ b/lib/server.dart @@ -17,9 +17,10 @@ class Realtime { const Realtime(); } -class AngelWebSocket { +class AngelWebSocket extends AngelPlugin { Angel _app; List _clients = []; + List get clients => new List.from(_clients, growable: false); List servicesAlreadyWired = []; String endpoint; @@ -153,8 +154,12 @@ class AngelWebSocket { } } + @override Future call(Angel app) async { - this._app = app; + this._app = app..container.singleton(this); + + if (runtimeType != AngelWebSocket) + app.container.singleton(this, as: AngelWebSocket); // Set up services wireAllServices(app); @@ -177,6 +182,8 @@ class AngelWebSocket { var socket = new WebSocketContext(ws, req, res); await onConnect(socket); + req.params['socket'] = socket; + ws.listen((data) { onData(socket, data); }, onDone: () { diff --git a/test/common.dart b/test/common.dart index cb09c5c0..bf4492f1 100644 --- a/test/common.dart +++ b/test/common.dart @@ -1,7 +1,7 @@ import 'dart:async'; import 'dart:io'; import 'package:angel_framework/angel_framework.dart'; -import 'package:angel_framework/defs.dart'; +import 'package:angel_framework/src/defs.dart'; class Todo extends MemoryModel { String text;