promise-ws
Advanced tools
Comparing version 0.1.0 to 0.2.0
@@ -29,9 +29,29 @@ 'use strict'; | ||
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } | ||
const parseOptions = function parseOptions(addressOrOptions) { | ||
if (typeof addressOrOptions === 'string') { | ||
return { address: addressOrOptions }; | ||
} else { | ||
const address = addressOrOptions.address, | ||
protocols = addressOrOptions.protocols, | ||
options = _objectWithoutProperties(addressOrOptions, ['address', 'protocols']); | ||
return { address, protocols, options }; | ||
} | ||
}; | ||
class Client extends _events2.default { | ||
static create(address) { | ||
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
static create(addressOrOptions) { | ||
let handlers = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
return new Promise((resolve, reject) => { | ||
const ws = new _ws2.default(address); | ||
const connection = new Client(ws, _extends({}, options, { | ||
var _parseOptions = parseOptions(addressOrOptions); | ||
const address = _parseOptions.address, | ||
protocols = _parseOptions.protocols, | ||
options = _parseOptions.options; | ||
const ws = new _ws2.default(address, protocols, options); | ||
const connection = new Client(ws, _extends({}, handlers, { | ||
onOpen() { | ||
@@ -45,7 +65,9 @@ resolve(connection); | ||
static connect(address, waitUntil) { | ||
static connect(addressOrOptions, waitUntil) { | ||
return new Promise((() => { | ||
var _ref = _asyncToGenerator(function* (resolve, reject) { | ||
try { | ||
const client = yield Client.create(address, { onClose: reject }); | ||
const client = yield Client.create(addressOrOptions, { | ||
onClose: reject | ||
}); | ||
const res = yield waitUntil(client); | ||
@@ -64,3 +86,3 @@ resolve(res); | ||
static autoReconnect(address, waitUntil) { | ||
static autoReconnect(addressOrOptions, waitUntil) { | ||
var _arguments = arguments; | ||
@@ -71,7 +93,7 @@ return _asyncToGenerator(function* () { | ||
try { | ||
return yield Client.connect(address, waitUntil); | ||
return yield Client.connect(addressOrOptions, waitUntil); | ||
} catch (err) { | ||
if (err.message === 'CLOSE') { | ||
yield (0, _delay2.default)(reconnectDelay); | ||
return Client.autoReconnect(address, waitUntil); | ||
return Client.autoReconnect(addressOrOptions, waitUntil); | ||
} else { | ||
@@ -85,11 +107,13 @@ throw err; | ||
constructor(ws) { | ||
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var _this; | ||
super(); | ||
let handlers = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
const onClose = options.onClose, | ||
onOpen = options.onOpen, | ||
onError = options.onError; | ||
_this = super(); | ||
const onClose = handlers.onClose, | ||
onOpen = handlers.onOpen, | ||
onError = handlers.onError; | ||
this._inputCallbacks = new Map(); | ||
@@ -102,42 +126,70 @@ this._outputCallbacks = new Map(); | ||
ws.on('message', message => { | ||
try { | ||
var _JSON$parse = JSON.parse(message); | ||
ws.on('message', (() => { | ||
var _ref2 = _asyncToGenerator(function* (message) { | ||
try { | ||
var _JSON$parse = JSON.parse(message); | ||
const _id = _JSON$parse._id, | ||
name = _JSON$parse.name, | ||
args = _JSON$parse.args, | ||
responseData = _JSON$parse.responseData; | ||
const _id = _JSON$parse._id, | ||
name = _JSON$parse.name, | ||
args = _JSON$parse.args, | ||
responseData = _JSON$parse.responseData; | ||
if (!_id) { | ||
throw new Error(); | ||
} | ||
/* istanbul ignore if */ | ||
if (name) { | ||
var _replyEmitter; | ||
if (!_id) { | ||
throw new Error(); | ||
} | ||
const hasListener = this._replyEmitter.listenerCount(name) > 0; | ||
if (hasListener) { | ||
this._inputCallbacks.set(_id, responseData => { | ||
this._inputCallbacks.delete(_id); | ||
ws.send(JSON.stringify({ _id, responseData })); | ||
}); | ||
} else { | ||
ws.send(JSON.stringify({ _id })); | ||
/* istanbul ignore else */ | ||
if (name) { | ||
var _replyEmitter; | ||
const send = function send(data) { | ||
return new Promise((resolve, reject) => { | ||
ws.send(JSON.stringify(data), err => { | ||
/* istanbul ignore if */ | ||
if (err) { | ||
reject(err); | ||
} else { | ||
resolve(); | ||
} | ||
}); | ||
}); | ||
}; | ||
const hasListener = _this._replyEmitter.listenerCount(name) > 0; | ||
if (hasListener) { | ||
_this._inputCallbacks.set(_id, (() => { | ||
var _ref3 = _asyncToGenerator(function* (responseData) { | ||
_this._inputCallbacks.delete(_id); | ||
yield send({ _id, responseData }); | ||
}); | ||
return function (_x7) { | ||
return _ref3.apply(this, arguments); | ||
}; | ||
})()); | ||
} else { | ||
yield send({ _id }); | ||
} | ||
(_replyEmitter = _this._replyEmitter).emit.apply(_replyEmitter, [name, _id].concat(_toConsumableArray(args))); | ||
} else if (_this._outputCallbacks.has(_id)) { | ||
const response = _this._outputCallbacks.get(_id); | ||
response(responseData); | ||
} | ||
(_replyEmitter = this._replyEmitter).emit.apply(_replyEmitter, [name, _id].concat(_toConsumableArray(args))); | ||
} else if (this._outputCallbacks.has(_id)) { | ||
const response = this._outputCallbacks.get(_id); | ||
response(responseData); | ||
} catch (err) { | ||
/* istanbul ignore next */ | ||
// this._replyEmitter.emit('message', message); | ||
// TODO | ||
console.error(err); | ||
} | ||
} catch (err) { | ||
/* istanbul ignore next */ | ||
}); | ||
// this._replyEmitter.emit('message', message); | ||
return function (_x6) { | ||
return _ref2.apply(this, arguments); | ||
}; | ||
})()); | ||
// TODO | ||
console.error(err); | ||
} | ||
}); | ||
if ((0, _utils.isFunction)(onClose)) { | ||
@@ -172,7 +224,7 @@ ws.on('close', () => { | ||
onReply(name, listener) { | ||
var _this = this; | ||
onReply(name, listener, errorHandler) { | ||
var _this2 = this; | ||
const finalListener = (() => { | ||
var _ref2 = _asyncToGenerator(function* (_id) { | ||
var _ref4 = _asyncToGenerator(function* (_id) { | ||
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | ||
@@ -182,12 +234,20 @@ args[_key - 1] = arguments[_key]; | ||
const responseData = yield listener.apply(undefined, _toConsumableArray(args)); | ||
try { | ||
const responseData = yield listener.apply(undefined, _toConsumableArray(args)); | ||
if (_this._inputCallbacks.has(_id)) { | ||
const handler = _this._inputCallbacks.get(_id); | ||
handler(responseData); | ||
/* istanbul ignore else */ | ||
if (_this2._inputCallbacks.has(_id)) { | ||
const handler = _this2._inputCallbacks.get(_id); | ||
yield handler(responseData); | ||
} | ||
} catch (err) { | ||
/* istanbul ignore else */ | ||
if ((0, _utils.isFunction)(errorHandler)) { | ||
errorHandler(err); | ||
} | ||
} | ||
}); | ||
return function finalListener(_x6) { | ||
return _ref2.apply(this, arguments); | ||
return function finalListener(_x8) { | ||
return _ref4.apply(this, arguments); | ||
}; | ||
@@ -208,8 +268,8 @@ })(); | ||
replyOnce(name, listener) { | ||
var _this2 = this; | ||
replyOnce(name, listener, errorHandler) { | ||
var _this3 = this; | ||
const finalListener = (() => { | ||
var _ref3 = _asyncToGenerator(function* () { | ||
_this2.removeReply(name, listener); | ||
var _ref5 = _asyncToGenerator(function* () { | ||
_this3.removeReply(name, listener); | ||
return listener.apply(undefined, arguments); | ||
@@ -219,11 +279,13 @@ }); | ||
return function finalListener() { | ||
return _ref3.apply(this, arguments); | ||
return _ref5.apply(this, arguments); | ||
}; | ||
})(); | ||
this.onReply(name, finalListener); | ||
this.onReply(name, finalListener, errorHandler); | ||
// to make listener removable | ||
const onReply = this._listeners.get(finalListener); | ||
const delted = this._listeners.delete(finalListener); | ||
if (delted) { | ||
const deleted = this._listeners.delete(finalListener); | ||
/* istanbul ignore else */ | ||
if (deleted) { | ||
this._listeners.set(listener, onReply); | ||
@@ -254,2 +316,4 @@ } | ||
const finalListener = this._listeners.get(listener); | ||
/* istanbul ignore else */ | ||
if (finalListener) { | ||
@@ -259,2 +323,3 @@ this._listeners.delete(listener); | ||
} | ||
return this; | ||
@@ -271,3 +336,2 @@ } | ||
const _id = ++this._lastId; | ||
this._outputCallbacks.set(_id, responseData => { | ||
@@ -277,6 +341,9 @@ this._outputCallbacks.delete(_id); | ||
}); | ||
this._ws.send(JSON.stringify({ _id, name, args })); | ||
this._ws.send(JSON.stringify({ _id, name, args }), err => { | ||
/* istanbul ignore next */ | ||
if (err) { | ||
reject(err); | ||
} | ||
}); | ||
} catch (err) { | ||
/* istanbul ignore next */ | ||
@@ -283,0 +350,0 @@ reject(err); |
@@ -47,4 +47,11 @@ 'use strict'; | ||
constructor(options, callback) { | ||
if (!(0, _utils.isObject)(options)) { | ||
throw new Error('Missing option argument, expected an object.'); | ||
} | ||
super(); | ||
const server = options.server, | ||
noServer = options.noServer; | ||
const wss = new _ws2.default.Server(_extends({}, options, { | ||
@@ -93,5 +100,2 @@ clientTracking: true | ||
wss.on('listening', callback); | ||
wss.on('error', callback); | ||
const forward = eventType => { | ||
@@ -106,2 +110,9 @@ wss.on(eventType, this.emit.bind(this, eventType)); | ||
forward('headers'); | ||
if (noServer || server && server.listening) { | ||
process.nextTick(callback); | ||
} else { | ||
wss.on('listening', callback); | ||
} | ||
wss.on('error', callback); | ||
} | ||
@@ -131,4 +142,4 @@ | ||
addReply(name, listener) { | ||
return this.onReply(name, listener); | ||
addReply() { | ||
return this.onReply.apply(this, arguments); | ||
} | ||
@@ -141,6 +152,9 @@ | ||
_forEach(iterator) { | ||
this._wss.clients.forEach(ws => { | ||
_createClientsIterator(iterator) { | ||
return ws => { | ||
/* istanbul ignore else */ | ||
if (ws.readyState === _ws2.default.OPEN) { | ||
const client = this.clients.get(ws); | ||
/* istanbul ignore else */ | ||
if (client) { | ||
@@ -150,6 +164,15 @@ iterator(client); | ||
} | ||
}); | ||
}; | ||
} | ||
onConnection(iterator) { | ||
this._wss.on('connection', this._createClientsIterator(iterator)); | ||
} | ||
_forEach(iterator) { | ||
this._wss.clients.forEach(this._createClientsIterator(iterator)); | ||
} | ||
removeReply(name, listener) { | ||
/* istanbul ignore else */ | ||
if (this._names.has(name)) { | ||
@@ -156,0 +179,0 @@ const listeners = this._names.get(name); |
@@ -7,2 +7,3 @@ 'use strict'; | ||
exports.isFunction = isFunction; | ||
exports.isObject = isObject; | ||
exports.noop = noop; | ||
@@ -13,2 +14,6 @@ function isFunction(target) { | ||
function isObject(target) { | ||
return typeof target === 'object'; | ||
} | ||
function noop() {} |
{ | ||
"name": "promise-ws", | ||
"description": "A Promise-Based WebSocket implementation for Node.js", | ||
"version": "0.1.0", | ||
"version": "0.2.0", | ||
"main": "lib/index", | ||
@@ -37,3 +37,3 @@ "files": [ | ||
"pify": "^3.0.0", | ||
"ws": "^3.2.0" | ||
"ws": "^5.0.0" | ||
}, | ||
@@ -43,3 +43,2 @@ "devDependencies": { | ||
"babel-core": "^6.13.2", | ||
"babel-eslint": "^7.2.3", | ||
"babel-jest": "^20.0.3", | ||
@@ -55,10 +54,6 @@ "babel-plugin-transform-es2015-destructuring": "^6.19.0", | ||
"cross-env": "^4.0.0", | ||
"eslint": "^3.19.0", | ||
"eslint-config-standard": "^10.2.1", | ||
"eslint-plugin-import": "^2.2.0", | ||
"eslint-plugin-jest": "^19.0.1", | ||
"eslint-plugin-node": "^4.2.2", | ||
"eslint-plugin-promise": "^3.5.0", | ||
"eslint-plugin-standard": "^3.0.1", | ||
"eslint": "^4.18.2", | ||
"eslint-config-cantonjs": "^0.2.0", | ||
"jest": "^20.0.4", | ||
"prettier-eslint-cli": "^4.7.1", | ||
"rimraf": "^2.5.4" | ||
@@ -65,0 +60,0 @@ }, |
316
README.md
@@ -7,45 +7,44 @@ # promise-ws | ||
A promise based WebSocket implementation for Node.js. Built on top of [ws](https://github.com/websockets/ws) | ||
A promise based WebSocket implementation for Node.js. Built on top of | ||
[ws](https://github.com/websockets/ws) | ||
## Table of Contents | ||
<!-- MarkdownTOC autolink="true" bracket="round" --> | ||
<!-- MarkdownTOC bracket="round" --> | ||
- [Usage](#usage) | ||
- [Installation](#installation) | ||
- [API Reference](#api-reference) | ||
- [Server.create\(options\)](#servercreateoptions) | ||
- [Server Events](#server-events) | ||
- [server#onReply\(name, response\)](#serveronreplyname-response) | ||
- [server#addReply\(name, response\)](#serveraddreplyname-response) | ||
- [server#reply\(name, response\)](#serverreplyname-response) | ||
- [server#removeReply\(name, response\)](#serverremovereplyname-response) | ||
- [server#replyCount\(name\)](#serverreplycountname) | ||
- [server#request\(name\[, ...args\]\)](#serverrequestname-args) | ||
- [server#wss\(\)](#serverwss) | ||
- [server#close\(\)](#serverclose) | ||
- [server#clients](#serverclients) | ||
- [Client.create\(address\[, options\]\)](#clientcreateaddress-options) | ||
- [Client.connect\(address, waitUntil\)](#clientconnectaddress-waituntil) | ||
- [Client.autoReconnect\(address, waitUntil\[, delay\]\)](#clientautoreconnectaddress-waituntil-delay) | ||
- [Client Events](#client-events) | ||
- [client#onReply\(name, response\)](#clientonreplyname-response) | ||
- [client#addReply\(name, response\)](#clientaddreplyname-response) | ||
- [client#reply\(name, response\)](#clientreplyname-response) | ||
- [client#removeReply\(name, response\)](#clientremovereplyname-response) | ||
- [client#replyCount\(name\)](#clientreplycountname) | ||
- [client#request\(name\[, ...args\]\)](#clientrequestname-args) | ||
- [client#ws\(\)](#clientws) | ||
- [client#close\(\)](#clientclose) | ||
- [License](#license) | ||
* [Usage](#usage) | ||
* [Installation](#installation) | ||
* [API Reference](#api-reference) | ||
* [Server.create\(options\)](#servercreateoptions) | ||
* [Server Events](#server-events) | ||
* [server#onConnection\(callback\)](#serveronconnectioncallback) | ||
* [server#onReply\(name, response\)](#serveronreplyname-response) | ||
* [server#addReply\(name, response\)](#serveraddreplyname-response) | ||
* [server#reply\(name, response\)](#serverreplyname-response) | ||
* [server#removeReply\(name, response\)](#serverremovereplyname-response) | ||
* [server#replyCount\(name\)](#serverreplycountname) | ||
* [server#request\(name\[, ...args\]\)](#serverrequestname-args) | ||
* [server#wss\(\)](#serverwss) | ||
* [server#close\(\)](#serverclose) | ||
* [server#clients](#serverclients) | ||
* [Client.create\(address\[, options\]\)](#clientcreateaddress-options) | ||
* [Client.connect\(address, waitUntil\)](#clientconnectaddress-waituntil) | ||
* [Client.autoReconnect\(address, waitUntil\[, delay\]\)](#clientautoreconnectaddress-waituntil-delay) | ||
* [Client Events](#client-events) | ||
* [client#onReply\(name, response\[, errorHandler\]\)](#clientonreplyname-response-errorhandler) | ||
* [client#addReply\(name, response\[, errorHandler\]\)](#clientaddreplyname-response-errorhandler) | ||
* [client#reply\(name, response\[, errorHandler\]\)](#clientreplyname-response-errorhandler) | ||
* [client#removeReply\(name, response\[, errorHandler\]\)](#clientremovereplyname-response-errorhandler) | ||
* [client#replyCount\(name\)](#clientreplycountname) | ||
* [client#request\(name\[, ...args\]\)](#clientrequestname-args) | ||
* [client#ws\(\)](#clientws) | ||
* [client#close\(\)](#clientclose) | ||
* [License](#license) | ||
<!-- /MarkdownTOC --> | ||
<a name="usage"></a> | ||
## Usage | ||
```js | ||
import { Server, Client } from 'promise-ws'; | ||
import { Server, Client } from "promise-ws"; | ||
@@ -55,17 +54,15 @@ (async function main() { | ||
const server = await Server.create({ port }); | ||
server.reply('say', async (data) => { | ||
console.log('data'); /* 'hello' */ | ||
return 'world'; | ||
server.reply("say", async data => { | ||
console.log("data"); /* 'hello' */ | ||
return "world"; | ||
}); | ||
const url = `ws://127.0.0.1:${port}`; | ||
await Client.autoReconnect(url, async (client) => { | ||
const response = await client.request('say', 'hello'); | ||
await Client.autoReconnect(url, async client => { | ||
const response = await client.request("say", "hello"); | ||
console.log(response); /* 'world' */ | ||
}); | ||
}()); | ||
})(); | ||
``` | ||
<a name="installation"></a> | ||
## Installation | ||
@@ -77,7 +74,4 @@ | ||
<a name="api-reference"></a> | ||
## API Reference | ||
<a name="servercreateoptions"></a> | ||
### Server.create(options) | ||
@@ -87,30 +81,40 @@ | ||
1. `options` \<Object\>: All options will be passed to [WebSocket.Server(opsions)](https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback), except for `clientTracking`, which will always be `true`. | ||
1. `options` \<Object\>: All options will be passed to | ||
[WebSocket.Server(opsions)](https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback), | ||
except for `clientTracking`, which will always be `true`. | ||
###### Returns | ||
- `server` \<Promise\<Server\>\> | ||
* `server` \<Promise\<Server\>\> | ||
Create a WebSocket server | ||
<a name="server-events"></a> | ||
### Server Events | ||
Server extends [EventEmitter](https://nodejs.org/api/events.html), which forwards these events from [WebSocket.Server](https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocketserver): | ||
Server extends [EventEmitter](https://nodejs.org/api/events.html), which | ||
forwards these events from | ||
[WebSocket.Server](https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocketserver): | ||
- [connection](https://github.com/websockets/ws/blob/master/doc/ws.md#event-connection) | ||
- [error](https://github.com/websockets/ws/blob/master/doc/ws.md#event-error) | ||
- [headers](https://github.com/websockets/ws/blob/master/doc/ws.md#event-headers) | ||
* [connection](https://github.com/websockets/ws/blob/master/doc/ws.md#event-connection) | ||
* [error](https://github.com/websockets/ws/blob/master/doc/ws.md#event-error) | ||
* [headers](https://github.com/websockets/ws/blob/master/doc/ws.md#event-headers) | ||
### server#onConnection(callback) | ||
<a name="serveronreplyname-response"></a> | ||
1. `callback` \<Function\>: The callback function, the only argument is | ||
`client`. | ||
Like `server.on('connection', callback)`, the only difference is the callback | ||
argument is `client` but not `ws`. | ||
### server#onReply(name, response) | ||
1. `name` \<String\>: The name of the event | ||
2. `response` \<Function\>: The callback function. Should return a promise | ||
1. `name` \<String\>: The name of the event | ||
2. `response` \<Function\>: The callback function. Should return a promise | ||
Add a reply function. Will be called when client calls `request()`. The response function arguments are the same with `client.request(name, ...arguments)` arguments. The returning value in response would be reply to the issuer client request function. | ||
Add a reply function. Will be called when client calls `request()`. The response | ||
function arguments are the same with `client.request(name, ...arguments)` | ||
arguments. The returning value in response would be reply to the issuer client | ||
request function. | ||
<a name="serveraddreplyname-response"></a> | ||
### server#addReply(name, response) | ||
@@ -120,4 +124,2 @@ | ||
<a name="serverreplyname-response"></a> | ||
### server#reply(name, response) | ||
@@ -127,21 +129,15 @@ | ||
<a name="serverremovereplyname-response"></a> | ||
### server#removeReply(name, response) | ||
1. `name` \<String\>: The name of the event | ||
2. `response` \<Function\>: The callback function | ||
1. `name` \<String\>: The name of the event | ||
2. `response` \<Function\>: The callback function | ||
Remove a reply function. | ||
<a name="serverreplycountname"></a> | ||
### server#replyCount(name) | ||
1. `name` \<String\>: The name of the event | ||
1. `name` \<String\>: The name of the event | ||
Get reply function count by name. | ||
<a name="serverrequestname-args"></a> | ||
### server#request(name[, ...args]) | ||
@@ -151,13 +147,11 @@ | ||
1. `name` \<String\>: The name of the event | ||
2. `...args` \<Any\>: The request arguments | ||
1. `name` \<String\>: The name of the event | ||
2. `...args` \<Any\>: The request arguments | ||
###### Returns | ||
- `responseArray` \<Promise[\<Any\>]/>: Response array by clients replied | ||
* `responseArray` \<Promise[\<Any\>]/>: Response array by clients replied | ||
Request to all clients and wait for reply. | ||
<a name="serverwss"></a> | ||
### server#wss() | ||
@@ -167,8 +161,9 @@ | ||
- `wss` \<[WebSocketServer](https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocketserver)\> | ||
* `wss` | ||
\<[WebSocketServer](https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocketserver)\> | ||
Get \<[WebSocket.Server](https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocketserver)\> instance. | ||
Get | ||
\<[WebSocket.Server](https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocketserver)\> | ||
instance. | ||
<a name="serverclose"></a> | ||
### server#close() | ||
@@ -178,8 +173,6 @@ | ||
- \<Promise\> | ||
* \<Promise\> | ||
Stops the server. | ||
<a name="serverclients"></a> | ||
### server#clients | ||
@@ -189,7 +182,4 @@ | ||
--- | ||
<a name="clientcreateaddress-options"></a> | ||
### Client.create(address[, options]) | ||
@@ -199,9 +189,10 @@ | ||
1. `address` \<String\>: The address/URL to which to connect | ||
2. `options` \<Object\> | ||
- `onClose` \<Function\>: The callback function when client closed | ||
1. `address` \<String\>: The address/URL to which to connect | ||
2. `options` \<Object\> | ||
* `onClose` \<Function\>: The callback function when client closed | ||
###### Returns | ||
- `client` \<Promise\<Client\>\> | ||
* `client` \<Promise\<Client\>\> | ||
@@ -213,13 +204,14 @@ Create a WebSocket client. | ||
```js | ||
import { Client } from 'promise-ws'; | ||
import { Client } from "promise-ws"; | ||
(async function main() { | ||
const client = await Client.create('ws://127.0.0.1:3000', { | ||
onClose() { console.error('server closed'); } | ||
const client = await Client.create("ws://127.0.0.1:3000", { | ||
onClose() { | ||
console.error("server closed"); | ||
} | ||
}); | ||
/* do something... */ | ||
}()); | ||
})(); | ||
``` | ||
<a name="clientconnectaddress-waituntil"></a> | ||
### Client.connect(address, waitUntil) | ||
@@ -229,8 +221,9 @@ | ||
1. `address` \<String\>: The address/URL to which to connect | ||
2. `waitUntil` \<Function\>: The main function to handle client. Should return a promise | ||
1. `address` \<String\>: The address/URL to which to connect | ||
2. `waitUntil` \<Function\>: The main function to handle client. Should return | ||
a promise | ||
###### Returns | ||
- \<Promise\<Any\>\> | ||
* \<Promise\<Any\>\> | ||
@@ -241,5 +234,7 @@ Create a WebSocket client and pass to the first argumet of `waitUntil` function. | ||
- The `waitUntil` function returns a value. The value will be returned to `Client.connect()` as a promise | ||
- The `waitUntil` function throws an error. This will throw a rejection | ||
- The server closed. This will throw a rejection, and the error message will be "CLOSE" | ||
* The `waitUntil` function returns a value. The value will be returned to | ||
`Client.connect()` as a promise | ||
* The `waitUntil` function throws an error. This will throw a rejection | ||
* The server closed. This will throw a rejection, and the error message will be | ||
"CLOSE" | ||
@@ -249,21 +244,22 @@ ###### Example | ||
```js | ||
import { Client } from 'promise-ws'; | ||
import { Client } from "promise-ws"; | ||
(async function main() { | ||
try { | ||
const url = 'ws://127.0.0.1:3000'; | ||
const res = await Client.connect(url, async (client) => { | ||
const url = "ws://127.0.0.1:3000"; | ||
const res = await Client.connect(url, async client => { | ||
/* do something... */ | ||
return 'chris'; | ||
return "chris"; | ||
}); | ||
console.log('res:', res); /* res: chris */ | ||
console.log("res:", res); /* res: chris */ | ||
} catch (err) { | ||
if (err.message === "CLOSE") { | ||
console.error("server closed"); | ||
} else { | ||
console.error(err); | ||
} | ||
} | ||
catch (err) { | ||
if (err.message === 'CLOSE') { console.error('server closed'); } | ||
else { console.error(err); } | ||
} | ||
}()); | ||
})(); | ||
``` | ||
<a name="clientautoreconnectaddress-waituntil-delay"></a> | ||
### Client.autoReconnect(address, waitUntil[, delay]) | ||
@@ -273,11 +269,13 @@ | ||
1. `address` \<String\>: The address/URL to which to connect | ||
2. `waitUntil` \<Function\>: The main function to handle client. Should return a promise | ||
3. `delay` \<Number\>: Delay time before reconnect in ms. Defaults to `1000` | ||
1. `address` \<String\>: The address/URL to which to connect | ||
2. `waitUntil` \<Function\>: The main function to handle client. Should return | ||
a promise | ||
3. `delay` \<Number\>: Delay time before reconnect in ms. Defaults to `1000` | ||
###### Returns | ||
- \<Promise\<Any\>\> | ||
* \<Promise\<Any\>\> | ||
Like `Client.connect()`, but if server closed, it will never throw error, and it will try to reconnect to the server after delay. | ||
Like `Client.connect()`, but if server closed, it will never throw error, and it | ||
will try to reconnect to the server after delay. | ||
@@ -287,72 +285,65 @@ ###### Example | ||
```js | ||
import { Client } from 'promise-ws'; | ||
import { Client } from "promise-ws"; | ||
(async function main() { | ||
try { | ||
const url = 'ws://127.0.0.1:3000'; | ||
const res = await Client.autoReconnect(url, async (client) => { | ||
const url = "ws://127.0.0.1:3000"; | ||
const res = await Client.autoReconnect(url, async client => { | ||
/* do something... */ | ||
return 'chris'; | ||
return "chris"; | ||
}); | ||
console.log('res:', res); /* res: chris */ | ||
} | ||
catch (err) { | ||
console.log("res:", res); /* res: chris */ | ||
} catch (err) { | ||
console.error(err); | ||
} | ||
}()); | ||
})(); | ||
``` | ||
<a name="client-events"></a> | ||
### Client Events | ||
Client extends [EventEmitter](https://nodejs.org/api/events.html), which forwards these events from [WebSocket.Client](https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocket): | ||
Client extends [EventEmitter](https://nodejs.org/api/events.html), which | ||
forwards these events from | ||
[WebSocket.Client](https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocket): | ||
- [close](https://github.com/websockets/ws/blob/master/doc/ws.md#event-close) | ||
- [error](https://github.com/websockets/ws/blob/master/doc/ws.md#event-error-1) | ||
- [headers](https://github.com/websockets/ws/blob/master/doc/ws.md#event-headers-1) | ||
- [message](https://github.com/websockets/ws/blob/master/doc/ws.md#event-message) | ||
- [open](https://github.com/websockets/ws/blob/master/doc/ws.md#event-open) | ||
- [ping](https://github.com/websockets/ws/blob/master/doc/ws.md#event-ping) | ||
- [pong](https://github.com/websockets/ws/blob/master/doc/ws.md#event-pong) | ||
- [unexpected-response](https://github.com/websockets/ws/blob/master/doc/ws.md#event-unexpected-response) | ||
* [close](https://github.com/websockets/ws/blob/master/doc/ws.md#event-close) | ||
* [error](https://github.com/websockets/ws/blob/master/doc/ws.md#event-error-1) | ||
* [headers](https://github.com/websockets/ws/blob/master/doc/ws.md#event-headers-1) | ||
* [message](https://github.com/websockets/ws/blob/master/doc/ws.md#event-message) | ||
* [open](https://github.com/websockets/ws/blob/master/doc/ws.md#event-open) | ||
* [ping](https://github.com/websockets/ws/blob/master/doc/ws.md#event-ping) | ||
* [pong](https://github.com/websockets/ws/blob/master/doc/ws.md#event-pong) | ||
* [unexpected-response](https://github.com/websockets/ws/blob/master/doc/ws.md#event-unexpected-response) | ||
### client#onReply(name, response[, errorHandler]) | ||
<a name="clientonreplyname-response"></a> | ||
### client#onReply(name, response) | ||
1. `name` \<String\>: The name of the event | ||
2. `response` \<Function\>: The callback function. Should return a promise | ||
3. `errorHandler` \<Function\>: The error handler function | ||
1. `name` \<String\>: The name of the event | ||
2. `response` \<Function\>: The callback function. Should return a promise | ||
Add a reply function. Will be called when server calls `request()`. The response | ||
function arguments are the same with `server.request(name, ...arguments)` | ||
arguments. The returning value in response would be reply to the server request | ||
function. | ||
Add a reply function. Will be called when server calls `request()`. The response function arguments are the same with `server.request(name, ...arguments)` arguments. The returning value in response would be reply to the server request function. | ||
### client#addReply(name, response[, errorHandler]) | ||
<a name="clientaddreplyname-response"></a> | ||
### client#addReply(name, response) | ||
Alias for `client#onReply(name, response)` | ||
### client#reply(name, response[, errorHandler]) | ||
<a name="clientreplyname-response"></a> | ||
### client#reply(name, response) | ||
Alias for `client#onReply(name, response)` | ||
### client#removeReply(name, response[, errorHandler]) | ||
<a name="clientremovereplyname-response"></a> | ||
### client#removeReply(name, response) | ||
1. `name` \<String\>: The name of the event | ||
2. `response` \<Function\>: The callback function | ||
1. `name` \<String\>: The name of the event | ||
2. `response` \<Function\>: The callback function | ||
Remove a reply function. | ||
<a name="clientreplycountname"></a> | ||
### client#replyCount(name) | ||
1. `name` \<String\>: The name of the event | ||
1. `name` \<String\>: The name of the event | ||
Get reply function count by name. | ||
<a name="clientrequestname-args"></a> | ||
### client#request(name[, ...args]) | ||
@@ -362,13 +353,11 @@ | ||
1. `name` \<String\>: The name of the event | ||
2. `...args` \<Any\>: The request arguments | ||
1. `name` \<String\>: The name of the event | ||
2. `...args` \<Any\>: The request arguments | ||
###### Returns | ||
- `responseData` \<Promise\<Any\>/>: Response data by server replied | ||
* `responseData` \<Promise\<Any\>/>: Response data by server replied | ||
Request to all clients and wait for reply. | ||
<a name="clientws"></a> | ||
### client#ws() | ||
@@ -378,8 +367,9 @@ | ||
- `ws` \<[WebSocketClient](https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocketclient)\> | ||
* `ws` | ||
\<[WebSocketClient](https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocketclient)\> | ||
Get \<[WebSocket.Client](https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocketclient)\> instance. | ||
Get | ||
\<[WebSocket.Client](https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocketclient)\> | ||
instance. | ||
<a name="clientclose"></a> | ||
### client#close() | ||
@@ -389,6 +379,4 @@ | ||
<a name="license"></a> | ||
## License | ||
MIT |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
28001
17
468
363
+ Addedws@5.2.4(transitive)
- Removedsafe-buffer@5.1.2(transitive)
- Removedultron@1.1.1(transitive)
- Removedws@3.3.3(transitive)
Updatedws@^5.0.0