Skip to content

Commit

Permalink
v3.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
Stanislav Utkin committed Nov 15, 2018
1 parent 727e05d commit bf528ce
Show file tree
Hide file tree
Showing 16 changed files with 1,633 additions and 1,293 deletions.
9 changes: 2 additions & 7 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
"parserOptions": {
"ecmaVersion": 8,
"ecmaFeatures": {
"impliedStrict": true
"impliedStrict": true,
"experimentalObjectRestSpread": true
}
},
"extends": [
Expand Down Expand Up @@ -200,12 +201,6 @@
"no-new-require": [
"error"
],
"no-param-reassign": [
"error",
{
"props": false
}
],
"no-prototype-builtins": [
"error"
],
Expand Down
84 changes: 49 additions & 35 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,51 +9,58 @@ specific message.

**Note**: This module does not work in the browser. All the basic ws documentation is
[here](https://github.com/websockets/ws/blob/master/README.md). This module only adds new methods and properties
and does not affect the old ones(except packMessage and unpackMessage methods, which can be found here).
and does not affect the old ones(except Send method - it became asynchronous).

## Table of Contents

* [Installing](#installing)
* [WebSocketAwait settings](#websocketawait-settings)
* [API docs](#api-docs)
* [WebSocketAwait options](#websocket-await-options)
* [Usage examples](#usage-examples)
+ [Simple send and receive](#simple-send-and-receive)
+ [Sending to two servers](#sending-to-two-servers)
+ [With change attachAwaitId settings and catch Error](#with-change-attachawaitid-settings-and-catch-error)
+ [Сhain from sending and receiving a message](#Сhain-from-sending-and-receiving-a-message)
+ [Сhain from sending and receiving a message](#chain-from-sending-and-receiving-a-message)
* [Suggestions and questions](#suggestions-and-questions)
* [Changelog](#changelog)
* [License](#license)

## Installing
## <a name="installing">Installing</a>

```
npm install --save ws-await
npm install ws-await
```

## API docs
## <a name="api-docs">API docs</a>

See [`/doc/ws.md`](./doc/wsAwait.md) to view detailed information.

## WebSocketAwait settings
## <a name="websocket-await-options">WebSocketAwait options</a>

New methods and options have been added to this module. Be careful when using them: read the
[`API documentation`](./doc/wsAwait.md) carefully.

The module includes several settings and options for convenient operation. The method responsible for their installation
is called `setSettings`. Use only this method to set the settings and options. Below is an example work `setSettings`:
The module includes several settings and options for convenient operation. All options are passed as options(for both
`client` and `server`):

```js
ws.setSettings({
awaitTimeout: 10,
leaveAwaitId: true,
nameAwaitId: 'awaitId',
const WebSocketAwait = require('ws-await');

const options = {
awaitTimeout: 10000,
leaveAwaitId: false,
packMessage: data => JSON.stringify(data),
unpackMessage: data => JSON.parse(data),
generateAwaitId: () => `_${Math.random().toString(36).substr(2, 10)}`,
attachAwaitId: (data, id) => Object.assign({[this.nameAwaitId]: id}, data),
generateAwaitId: () => `_${Math.random()
.toString(36)
.substr(2, 10)}`,
attachAwaitId: (data, id) => Object.assign({awaitId: id}, data),
extractAwaitId: data => data &&
Object.prototype.hasOwnProperty.call(data, this.nameAwaitId) && data[this.nameAwaitId],
});
Object.prototype.hasOwnProperty.call(data, 'awaitId') && data.awaitId,
deleteAwaitId: data => delete data.awaitId,
};
const wss = new WebSocketAwait.Server({port: 5050, ...options});
const ws = new WebSocketAwait(`ws://localhost:5050`, options);
```

All settings and options presented above are set by default. Please consider this. For example, the `package
Expand All @@ -64,19 +71,28 @@ immediately before the message event is triggered. To disable these two methods
use the `setSettings` method and set the values of these methods to `null`. Disabling works only on these two methods!

```js
ws.setSettings({
const options = {
packMessage: null,
unpackMessage: null,
});
}
```

If you do not want to use the sendAwait and resAwait methods, set `extractAwaitId` to `null`(due to the fact that there
will be no checks for the presence of the `awaitId`(default) key , performance will be improved).

```js
const options = {
extractAwaitId: null,
}
```

All methods and properties are described in detail in the [`docs`](./doc/wsAwait.md).

## Usage examples
## <a name="usage-examples">Usage examples</a>

Examples are for informational purposes only!

### Simple send and receive
### <a name="simple-send-and-receive">Simple send and receive</a>

Send and receive a message waiting for a response.

Expand Down Expand Up @@ -106,7 +122,7 @@ ws.on('open', async () => {
});
```

### Sending to two servers
### <a name="sending-to-two-servers">Sending to two servers</a>

Sending to two servers and waiting for messages from them using `Promise.all()`.

Expand Down Expand Up @@ -155,32 +171,30 @@ setTimeout(async () => {
}, 1000);
```

### With change attachAwaitId settings and catch Error
### <a name="with-change-attachawaitid-settings-and-catch-error">With change attachAwaitId settings and catch Error</a>

Send and receive a message waiting for a response with change attachAwaitId settings and catch `Error`.

```js
const WebSocketAwait = require('ws-await');

const wss = new WebSocketAwait.Server({
port: 8080
port: 8080,
});

wss.on('connection', ws => {
ws.on('messageAwait', (msg, id) => {
console.log(`Server get messageAwait <<< ${msg.foo} and ${id}`);
ws.resAwait({
bar: 'foo'
bar: 'foo',
}, id);
});
});

const ws = new WebSocketAwait('ws://localhost:8080');

ws.setSettings({
const ws = new WebSocketAwait('ws://localhost:8080', {
attachAwaitId: (data, id) => {
if (typeof data === 'object') {
return Object.assign({[ws.nameAwaitId]: id}, data);
return Object.assign({awaitId: id}, data);
}
throw new Error('Data is not object');
},
Expand All @@ -189,7 +203,7 @@ ws.setSettings({
ws.on('open', async () => {
try {
const waitingOne = await ws.sendAwait({
foo: 'bar'
foo: 'bar',
});
console.log(`Client get waiting <<< ${waitingOne.bar}`);
const waitingTwo = await ws.sendAwait(10);
Expand All @@ -200,7 +214,7 @@ ws.on('open', async () => {
});
```

### Сhain from sending and receiving a message
### <a name="chain-from-sending-and-receiving-a-message">Сhain from sending and receiving a message</a>

Send and receive a message waiting for a response. The server also sends a waiting message to another server and sends
it to the first server when it receives a response.
Expand Down Expand Up @@ -249,15 +263,15 @@ wsOne.on('open', async () => {
});
```

## Suggestions and questions
## <a name="suggestions-and-questions">Suggestions and questions</a>

Send your suggestions and questions on [GitHub](https://github.com/stas-ut21/ws-await/issues) or send to email.
`[email protected]`
`[email protected]`.

## Changelog
## <a name="changelog">Changelog</a>

We're using the GitHub [releases](https://github.com/stas-ut21/ws-await/releases) for changelog entries.

## License
## <a name="license">License</a>

[MIT](LICENSE)
98 changes: 67 additions & 31 deletions doc/wsAwait.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,30 @@
# ws

Here we will consider only updates `Class: WebSocketAwait` as `Class: WebSocket.Server` uses it.
Here we will consider only updates `Class: WebSocketAwait` as `Class: WebSocket.Server` uses it.
`Class: WebSocket.Server` supports all options and methods described below!

**Note**: All the basic ws documentation is [here](https://github.com/websockets/ws/blob/master/doc/ws.md).This module
only adds new methods and properties and does not affect
the old ones(except packMessage and unpackMessage methods, which can be found here).
**Note**: All the basic ws documentation is [here](https://github.com/websockets/ws/blob/master/doc/ws.md).This module
only adds new methods and properties and does not affect the old ones(except `send` method - it became asynchronous).

## Class: WebSocketAwait

This class represents a WebSocket server. It extends the `WebSocket` class. The following describes the add-ons!
Full support for the old api!

### new WebSocket(address[, protocols][, options])

- `options` {Object}
- `awaitTimeout` {Number} The timeout waiting for a response.
- `leaveAwaitId` {Boolean} Whether to leave the identification parameter in the receiving data.
- `packMessage` {Function|Null} The message packaging function before sending.
- `unpackMessage` {Function|Null} The message un'packaging function after receiving.
- `generateAwaitId` {Function} The identification parameter generation function for sendAwait.
- `attachAwaitId` {Function} The function to installation identification parameter to sending messages.
- `extractAwaitId` {Function|Null} The function to extract identification parameter from incoming messages.
- `deleteAwaitId` {Function} The function to delete identification parameter from incoming messages.

If `protocols` is `Object` that `options` equal `protocols`!

### Event: 'messageAwait'

- `data` {*}
Expand All @@ -16,22 +33,11 @@ the old ones(except packMessage and unpackMessage methods, which can be found he
Emitted when a message is received from the server but resolution is not found by `awaitId`. The type of `data` is
unknown, as it depends on you how you will unpack the message.

### websocket.setSettings(opt)

- `opt` {Object} Options object.
- `opt.awaitTimeout` {Number} The timeout waiting for a response.
- `opt.nameAwaitId` {String} The name identification parameter for default attachAwaitId and extractAwaitId.
- `opt.leaveAwaitId` {Boolean} Whether to leave the identification parameter in the receiving data.
- `opt.packMessage` {Function} The message packaging function before sending.
- `opt.unpackMessage` {Function} The message un'packaging function after receiving.
- `opt.generateAwaitId` {Function} The identification parameter generation function for sendAwait.
- `opt.attachAwaitId` {Function} The function to installation identification parameter to sending messages.
- `opt.extractAwaitId` {Function} The function to extract identification parameter from incoming messages.
### websocket.awaitListSize

Setting module settings. Be careful: they are not checked for content, only pass type validation before they are replaced!
Settings `attachAwaitId` and `extractAwaitId` can use `websocket.nameAwaitId`.
Getter to get the number of awaits expected messages. May be useful for balancing.

### websocket.send(data[, options][, callback])
### websocket.send(data[, options])

- `data` {Any} The data to send (Do not forget about `packMessage`).
- `options` {Object}
Expand All @@ -43,10 +49,9 @@ Settings `attachAwaitId` and `extractAwaitId` can use `websocket.nameAwaitId`.
to `true` when `websocket` is not a server client.
- `fin` {Boolean} Specifies whether `data` is the last fragment of a message or
not. Defaults to `true`.
- `callback` {Function} An optional callback which is invoked when `data` is
written out.

Before shipping, checks for a `packMessage`, and if it has uses it on `data`, then sends it. Otherwise, just sends `data`.
It became asynchronous! Before shipping, checks for a `packMessage`, and if it has uses it on `data`, then sends it.
Otherwise, just sends `data`.

### websocket.sendAwait(data[, options])

Expand Down Expand Up @@ -89,13 +94,6 @@ at sending.

How long will the `sendAwait` method wait for a response.

### Option: nameAwaitId

- {String}

The name identification parameter for default attachAwaitId and extractAwaitId. Settings `attachAwaitId` and
`extractAwaitId` can use `websocket.nameAwaitId`.

### Option: leaveAwaitId

- {Boolean}
Expand All @@ -104,13 +102,13 @@ Whether to leave the identification parameter in the receiving data.

### Option: packMessage

- {Function}
- {Function|Null}

The message packaging function before sending. Occurs after `attachAwaitId`.

### Option: unpackMessage

- {Function}
- {Function|Null}

The message un'packaging function after receiving. Occurs before `extractAwaitId`.

Expand All @@ -128,6 +126,44 @@ The function to installation identification parameter to incoming messages. Occu

### Option: extractAwaitId

- {Function}
- {Function|Null}

The function to extract identification parameter from incoming messages. Occurs after `unpackMessage`.

### Option: deleteAwaitId

- {Function|Null}

The function to delete identification parameter from incoming messages. Occurs before emit `messageAwait` event.


### Error: WebSocketAwaitConnectionCloseError

- {Error}

When you close the connection, all pending messages sent will be rejected with this error.

### Error: WebSocketAwaitProcessedError

- {Error}

This error will be returned if the received message is not processed successfully.

### Error: WebSocketAwaitSendError

- {Error}

This error will be returned when sending failed in `sendAwait` and `resAwait` methods.(Method `Send` returns the
native error).

### Error: WebSocketAwaitTimeoutAwaitError

- {Error}

This error will be returned if you do not wait for a response within the specified interval `awaitTimeout`.

### Error: WebSocketAwaitValidationError

- {Error}

This error will be returned with invalid options (only options added within this module).
5 changes: 1 addition & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@

const WebSocketAwait = require('./lib/websocket.js');

const websocketDefaultPath = require.resolve('ws/lib/websocket.js');
require.cache[websocketDefaultPath].exports = WebSocketAwait;

WebSocketAwait.Server = require('ws/lib/websocket-server.js');
WebSocketAwait.Server = require('./lib/websocket-server.js');
WebSocketAwait.Receiver = require('ws/lib/receiver.js');
WebSocketAwait.Sender = require('ws/lib/sender.js');

Expand Down
Loading

0 comments on commit bf528ce

Please sign in to comment.