Skip to content

Commit

Permalink
feat(useWebSocket): Added support for optional protocols (vitest-dev#705
Browse files Browse the repository at this point in the history
)

* feat(useWebSocket): ✨  Added support for optional protocols parameter

Added support for an optional array parameter called protocols. This second parameter to the WebSocket constructor contains one or more protocol string to use e.g. subprotocols. If not provided, internally the parameter always default to an empty array (`[]`), so that was chosen as parameter initializer. More information can be found (here)[https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket].

* refactor(useWebSockets):  Moved protocols option to WebSocketOptions
  • Loading branch information
itpropro committed Sep 2, 2021
1 parent f573b95 commit 3816c29
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
21 changes: 19 additions & 2 deletions packages/core/useWebSocket/index.md
Expand Up @@ -69,6 +69,18 @@ const { status, data, close } = useWebSocket('ws://websocketurl', {
})
```

### Sub-protocols

List of one or more subprotocols to use, in this case soap and wamp.

```js
import { useWebSocket } from '@vueuse/core'

const { status, data, send, open, close } = useWebSocket('ws://websocketurl', {
protocols: ['soap'], // ['soap', 'wamp']
})
```

<!--FOOTER_STARTS-->
## Type Declarations

Expand Down Expand Up @@ -131,6 +143,12 @@ export interface WebSocketOptions {
* @default true
*/
immediate?: boolean
/**
* List of one or more sub-protocol strings
*
* @default []
*/
protocols?: string[],
}
export interface WebSocketResult<T> {
/**
Expand Down Expand Up @@ -172,13 +190,12 @@ export interface WebSocketResult<T> {
*/
export declare function useWebSocket<Data = any>(
url: string,
options?: WebSocketOptions
options?: WebSocketOptions,
): WebSocketResult<Data>
```

## Source

[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useWebSocket/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useWebSocket/index.md)


<!--FOOTER_ENDS-->
10 changes: 9 additions & 1 deletion packages/core/useWebSocket/index.ts
Expand Up @@ -62,6 +62,13 @@ export interface WebSocketOptions {
* @default true
*/
immediate?: boolean

/**
* List of one or more sub-protocol strings
*
* @default []
*/
protocols?: string[]
}

export interface WebSocketResult<T> {
Expand Down Expand Up @@ -124,6 +131,7 @@ export function useWebSocket<Data = any>(
onError,
onMessage,
immediate = true,
protocols = [],
} = options

const data: Ref<Data | null> = ref(null)
Expand Down Expand Up @@ -166,7 +174,7 @@ export function useWebSocket<Data = any>(
}

const _init = () => {
const ws = new WebSocket(url)
const ws = new WebSocket(url, protocols)
wsRef.value = ws
status.value = 'CONNECTING'
explicitlyClosed = false
Expand Down

0 comments on commit 3816c29

Please sign in to comment.