From 1d3101e00cf396e1de436a26c6834f9b48529804 Mon Sep 17 00:00:00 2001 From: Carlos Gottberg Date: Fri, 12 Jan 2018 20:36:00 -0300 Subject: [PATCH] Allow ws options to be passed to constructors (#107) This complies with the way ws behaves and is useful for specifying "low-level" ws options such as adding additional headers to the request (use case: authentication through jwt) --- src/angular-websocket.js | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/angular-websocket.js b/src/angular-websocket.js index 3f4e919..618c728 100644 --- a/src/angular-websocket.js +++ b/src/angular-websocket.js @@ -43,12 +43,12 @@ if (!Array.prototype.indexOf) { // $WebSocketProvider.$inject = ['$rootScope', '$q', '$timeout', '$websocketBackend']; function $WebSocketProvider($rootScope, $q, $timeout, $websocketBackend) { - function $WebSocket(url, protocols, options) { + function $WebSocket(url, protocols, options, wsOptions = {}) { if (!options && isObject(protocols) && !isArray(protocols)) { options = protocols; protocols = undefined; } - + this.wsOptions = wsOptions; this.protocols = protocols; this.url = url || 'Missing URL'; this.ssl = /(wss)/i.test(this.url); @@ -121,7 +121,7 @@ function $WebSocketProvider($rootScope, $q, $timeout, $websocketBackend) { $WebSocket.prototype._connect = function _connect(force) { if (force || !this.socket || this.socket.readyState !== this._readyStateConstants.OPEN) { - this.socket = $websocketBackend.create(this.url, this.protocols); + this.socket = $websocketBackend.create(this.url, this.protocols, this.wsOptions); this.socket.onmessage = angular.bind(this, this._onMessageHandler); this.socket.onopen = angular.bind(this, this._onOpenHandler); this.socket.onerror = angular.bind(this, this._onErrorHandler); @@ -367,13 +367,17 @@ function $WebSocketProvider($rootScope, $q, $timeout, $websocketBackend) { // $WebSocketBackendProvider.$inject = ['$log']; function $WebSocketBackendProvider($log) { - this.create = function create(url, protocols) { + this.create = function create(url, protocols, options) { var match = /wss?:\/\//.exec(url); if (!match) { throw new Error('Invalid url provided'); } + if (options) { + return new Socket(url, protocols, options); + } + if (protocols) { return new Socket(url, protocols); }