Skip to content

Commit dfff575

Browse files
james-deepsourceshivam-deepsourceyash-deepsource
authored
chore: merge url options (#16)
* chore: unify url options * docs: update info * chore: ensure consistency in the references to WebSocket * chore: supply runtime config via websocket key * test: update test suite * feat: update readme (#18) * feat: update readme * chore: update readme title Co-authored-by: James George <james@deepsource.io> Co-authored-by: James George <james@deepsource.io> * chore: update metadaa * docs: update info Co-authored-by: Yash Dave <87606277+yash-deepsource@users.noreply.github.com> Co-authored-by: Shivam Mishra <77610151+shivam-deepsource@users.noreply.github.com> Co-authored-by: Yash Dave <87606277+yash-deepsource@users.noreply.github.com>
1 parent dab9386 commit dfff575

File tree

7 files changed

+50
-63
lines changed

7 files changed

+50
-63
lines changed

README.md

Lines changed: 31 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,29 @@
1-
# nuxt-websocket
1+
<div align="center">
2+
<br>
3+
<br>
4+
5+
<h1>@deepsource/nuxt-websocket</h1>
26

37
[![DeepSource](https://deepsource.io/gh/deepsourcelabs/nuxt-websocket.svg/?label=active+issues&show_trend=true&token=aDA1Tz2a_4FxFsxvu4by_loF)](https://deepsource.io/gh/deepsourcelabs/nuxt-websocket/?ref=repository-badge) [![DeepSource](https://deepsource.io/gh/deepsourcelabs/nuxt-websocket.svg/?label=resolved+issues&show_trend=true&token=aDA1Tz2a_4FxFsxvu4by_loF)](https://deepsource.io/gh/deepsourcelabs/nuxt-websocket/?ref=repository-badge)
48

5-
> Nuxt.js module for websocket interactions.
9+
<p>A tiny Nuxt.js module for WebSocket interactions.</p>
10+
11+
</div>
612

713
## Setup
814

9-
1. Add `@deepsourcelabs/nuxt-websocket` dependency to your project
15+
1. Add `@deepsource/nuxt-websocket` dependency to your project.
1016

1117
```bash
12-
yarn add @deepsourcelabs/nuxt-websocket # or npm install @deepsourcelabs/nuxt-websocket
18+
yarn add @deepsource/nuxt-websocket # or npm install @deepsource/nuxt-websocket
1319
```
1420

15-
2. Add `@deepsourcelabs/nuxt-websocket` to the `modules` section of `nuxt.config.js`
21+
2. Add `@deepsource/nuxt-websocket` to the `modules` section of `nuxt.config.js`.
1622

1723
```js
1824
{
1925
modules: [
20-
'@deepsourcelabs/nuxt-websocket',
26+
'@deepsource/nuxt-websocket',
2127
],
2228
websocket: {
2329
// module options
@@ -27,44 +33,35 @@ yarn add @deepsourcelabs/nuxt-websocket # or npm install @deepsourcelabs/nuxt-we
2733

2834
## Options
2935

30-
You can pass different options using the `websocket` property in your `nuxt.config.js`:
36+
You can pass different options using the `websocket` property in your `nuxt.config.js`.
3137

3238
```js
3339
// nuxt.config.js
3440
export default {
3541
websocket: {
36-
// module options
42+
url: 'wss://echo.websocket.events/'
43+
reconnectInterval: 1000
3744
}
3845
};
3946
```
4047

41-
### `urlForDev`
42-
43-
- Default: `wss://echo.websocket.events/`
44-
45-
Defines the websocket URL to connect for local development.
46-
47-
### `urlForProd`
48-
49-
Defines the websocket URL to connect for production.
50-
51-
### `reconnectInterval`
52-
53-
- Default: `1000`
54-
55-
Defines the time interval after which a reconnection attempt takes place for a close event that isn't normal (code !== 1000). It should be less than 3s.
48+
| Parameter | Default | Description |
49+
| ------------------- | ------- | -------------------------------------------------------------------------------------------------------------- |
50+
| `url` | - | WebSocket URL to connect |
51+
| `reconnectInterval` | 1000 | The time interval after which a reconnection attempt takes place for a close event. It should be less than 3s. |
5652

5753
### Runtime Config
5854

59-
URL's for dev and prod supplied via runtime config takes priority:-
55+
You can also provide the URL via [runtime config](https://nuxtjs.org/docs/configuration-glossary/configuration-runtime-config/). It always takes precedence over the URL provided via options.
6056

6157
```js
6258
// nuxt.config.js
6359
export default {
6460
// Via Runtime config
6561
publicRuntimeConfig: {
66-
webSocketUrlForDev: process.env.WEBSOCKET_URL_FOR_DEV,
67-
webSocketUrlForProd: process.env.WEBSOCKET_URL_FOR_PROD
62+
websocket: {
63+
url: process.env.WEBSOCKET_URL
64+
}
6865
}
6966
};
7067
```
@@ -78,12 +75,12 @@ The following two plugins are injected into the Vue instance and are accessible
7875

7976
### `$socket`
8077

81-
Defines a global event bus.
78+
It's a Vue instance that's used as an event bus.
8279

8380
```js
8481
mounted() {
8582
this.$socket.$on('socket', (data) => {
86-
console.log(`got ${data} from websocket`);
83+
console.log(`got ${data} from WebSocket`);
8784
});
8885
}
8986

@@ -100,7 +97,7 @@ The WebSocketManager instance has access to the following methods:-
10097

10198
#### `connect(): void`
10299

103-
Establishes websocket connection. It defines handlers for message, close and error events.
100+
Establishes WebSocket connection. It defines handlers for message, close and error events.
104101

105102
```js
106103
this.$socketManager.connect();
@@ -110,7 +107,7 @@ this.$socketManager.connect();
110107
111108
#### `ready(): Promise<void>`
112109

113-
Returns a promise that resolves straightaway if the websocket connection is open. Or else, waits until the open event is fired.
110+
Returns a promise that resolves straightaway if the WebSocket connection is open. Or else, waits until the open event is fired.
114111

115112
```js
116113
await this.$socketManager.ready();
@@ -120,7 +117,7 @@ await this.$socketManager.ready();
120117
121118
#### `send (message: string | Record<string, unknown>): Promise<void>`
122119

123-
Waits for the websocket connection to be open if not already and transmits the data received.
120+
Waits for the WebSocket connection to be open if not already and transmits the data received.
124121

125122
```js
126123
await this.$socketManager.send({ event: "socket", data: "Hello world" });
@@ -134,7 +131,7 @@ Closes the WebSocket connection, optionally using code as the the WebSocket conn
134131
this.$socketManager.close();
135132
```
136133

137-
> The [onmessage](https://github.com/deepsourcelabs/nuxt-websocket/blob/main/src/templates/WebSocketManager.ts#L38-L45) handler expects data received from the server as either a string or an object of the shape `{ event: string, data: string }`.
134+
> The [message event handler](https://github.com/deepsourcelabs/nuxt-websocket/blob/main/src/templates/WebSocketManager.ts#L39-L46) expects data received from the server as either a string or an object of the shape `{ event: string, data: string }`.
138135
139136
```js
140137
// Data received of the type string.
@@ -147,6 +144,8 @@ this.$socket.on("message", () => {});
147144
this.$socket.on("socket", () => {});
148145
```
149146

147+
> The [close event handler](https://github.com/deepsourcelabs/nuxt-websocket/blob/main/src/templates/WebSocketManager.ts#L48-L64) attempts reconnection for a close event that is not normal ([connection close code](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code) other than 1000).
148+
150149
## Development
151150

152151
1. Clone this repository.

example/nuxt.config.js

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
11
export default {
22
buildModules: ['@nuxtjs/tailwindcss'],
3-
modules: ['@nuxt/typescript-build', '../src/module.ts'],
4-
websocket: {
5-
urlForProd: 'wss://sockets.deepsource.io/'
6-
}
3+
modules: ['@nuxt/typescript-build', '../src/module.ts']
74
}

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
2-
"name": "@deepsourcelabs/nuxt-websocket",
2+
"name": "@deepsource/nuxt-websocket",
33
"version": "0.0.0",
4-
"description": "Nuxt.js module for websocket interactions.",
4+
"description": "A tiny Nuxt.js module for WebSocket interactions.",
55
"keywords": [
66
"nuxt",
77
"module",

src/templates/WebSocketManager.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import Vue from 'vue'
22

33
/**
4-
* The WebSocketManager class that defines methods for websocket interaction.
4+
* The WebSocketManager class that defines methods for WebSocket interaction.
55
*/
66
export default class WebSocketManager {
77
url: string;
@@ -13,7 +13,7 @@ export default class WebSocketManager {
1313
* Constructor function for the WebSocketManager class.
1414
* Initializes properties and invokes connect method.
1515
*
16-
* @param {string} url The websocket URL to connect.
16+
* @param {string} url The WebSocket URL to connect.
1717
* @param {number} reconnectInterval Time in ms to reconnect.
1818
* @returns {WebSocketManager} The WebSocketManager instance.
1919
*/
@@ -71,7 +71,7 @@ export default class WebSocketManager {
7171
}
7272

7373
/**
74-
* Ensures the websocket connection is open.
74+
* Ensures the WebSocket connection is open.
7575
*
7676
* @returns {Promise<void>} A promise that resolves with no return value straightaway if the WebSocket connection is open.
7777
* Or else, waits until the open event is fired.
@@ -103,7 +103,7 @@ export default class WebSocketManager {
103103
}
104104

105105
/**
106-
* Closes the websocket connection.
106+
* Closes the WebSocket connection.
107107
*
108108
* @param {number | undefined} [code] The connection close code.
109109
* @param {string | undefined} [reason] The connection close reason.

src/templates/plugin.ts

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,25 +8,22 @@ import WebSocketManager from './WebSocketManager'
88

99
// mounted() {
1010
// this.$socket.$on(<event-name>, (data) => {
11-
// console.log(`got ${data} from websocket`)
11+
// console.log(`got ${data} from WebSocket`)
1212
// })
1313
// }
1414
//
1515
// Sending message
1616
// this.$socketManager.send({ event: 'socket', data: 'Hello' })
1717

1818
const reconnectInterval = Number('<%= options.reconnectInterval %>') || 1000
19-
const urlForProdFromOptions = '<%= options.urlForProd %>'
20-
const urlForDevFromOptions = '<%= options.urlForDev %>'
21-
19+
const urlFromOptions = '<%= options.url %>'
2220
export default ({ app }: { app: NuxtAppOptions }, inject: Inject): void => {
21+
/* istanbul ignore next */
22+
const runtimeConfig = (app.$config && app.$config.websocket) || {}
23+
2324
/* istanbul ignore next */
2425
const url =
25-
process.env.NODE_ENV === 'development'
26-
? app.$config.webSocketUrlForDev ||
27-
urlForDevFromOptions ||
28-
'wss://echo.websocket.events/'
29-
: app.$config.webSocketUrlForProd || urlForProdFromOptions
26+
runtimeConfig.url || urlFromOptions || 'wss://echo.websocket.events/'
3027

3128
const emitter = new Vue()
3229
const manager = new WebSocketManager(url, emitter, reconnectInterval)

test/module.test.ts

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,4 @@
1-
import {
2-
expectModuleToBeCalledWith,
3-
getNuxt,
4-
setupTest
5-
} from '@nuxt/test-utils'
1+
import { expectModuleToBeCalledWith, setupTest } from '@nuxt/test-utils'
62

73
describe('module', () => {
84
setupTest({
@@ -14,15 +10,15 @@ describe('module', () => {
1410
expectModuleToBeCalledWith('addPlugin', {
1511
src: 'src/templates/plugin.ts',
1612
fileName: 'nuxt-websocket/websocket.client.ts',
17-
options: getNuxt().options.websocket
13+
options: {}
1814
})
1915
})
2016

2117
test('should render the template', () => {
2218
expectModuleToBeCalledWith('addTemplate', {
2319
src: 'src/templates/WebSocketManager.ts',
2420
fileName: 'nuxt-websocket/WebSocketManager.ts',
25-
options: getNuxt().options.websocket
21+
options: {}
2622
})
2723
})
2824
})

test/plugin.test.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,16 @@ import plugin from '../src/templates/plugin'
77
const ctx = {
88
app: {
99
$config: {
10-
webSocketUrlForDev: 'wss://echo.websocket.events/'
10+
websocket: {
11+
url: 'wss://echo.websocket.events/'
12+
}
1113
}
1214
} as NuxtAppOptions
1315
}
1416
const inject: jest.MockedFunction<Inject> = jest.fn()
1517

1618
describe('plugin', () => {
1719
test('injects socket and socketManager plugins', () => {
18-
Object.defineProperty(process.env, 'NODE_ENV', {
19-
value: 'development'
20-
})
21-
2220
// Invoke plugin function.
2321
plugin(ctx, inject)
2422

0 commit comments

Comments
 (0)