Skip to content

Commit f53c2ca

Browse files
committed
feat: expose in public api ability to create a ws connection by specifying a WsSocketFactory, and referencing it in WsConnectionOptions.
WsConnectionOptions is a ConnectionOptions that exposes `wsFactory?: WsSocketFactory` This enables uses where the runtime is known to provide additional options that may be necessary for the connection but differ from standard W3C `new WebSocket(url)` usages. Signed-off-by: Alberto Ricart <[email protected]>
1 parent 0552c1d commit f53c2ca

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

core/src/internal_mod.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,8 @@ export { isIPV4OrHostname, Servers } from "./servers.ts";
146146

147147
export { wsconnect, wsUrlParseFn } from "./ws_transport.ts";
148148

149+
export type { WsConnectionOptions, WsSocketFactory } from "./ws_transport.ts";
150+
149151
export {
150152
AuthorizationError,
151153
ClosedConnectionError,

core/src/mod.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,4 +105,6 @@ export type {
105105
TlsOptions,
106106
TokenAuth,
107107
UserPass,
108+
WsConnectionOptions,
109+
WsSocketFactory,
108110
} from "./internal_mod.ts";

core/src/ws_transport.ts

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,26 @@ import { errors, InvalidArgumentError } from "./errors.ts";
3333
const VERSION = version;
3434
const LANG = "nats.ws";
3535

36+
/**
37+
* WsSocketFactory is a factory that returns a WebSocket and a boolean
38+
* indicating if the connection is encrypted. Client code is responsible
39+
* for creating a W3C WebSocket compliant transport.
40+
*
41+
* @param u the url to connect to
42+
* @param opts the connection options
43+
* @returns a promise that resolves to a WebSocket and a boolean indicating if
44+
* the connection is encrypted
45+
*/
3646
export type WsSocketFactory = (u: string, opts: ConnectionOptions) => Promise<{
3747
socket: WebSocket;
3848
encrypted: boolean;
3949
}>;
40-
interface WsConnectionOptions extends ConnectionOptions {
50+
51+
/**
52+
* WsConnectionOptions exposes wsconnect specific options not applicable to
53+
* other transports.
54+
*/
55+
export interface WsConnectionOptions extends ConnectionOptions {
4156
wsFactory?: WsSocketFactory;
4257
}
4358

@@ -334,7 +349,7 @@ export function wsUrlParseFn(u: string, encrypted?: boolean): string {
334349
}
335350

336351
export function wsconnect(
337-
opts: ConnectionOptions = {},
352+
opts: ConnectionOptions | WsConnectionOptions = {},
338353
): Promise<NatsConnection> {
339354
setTransportFactory({
340355
defaultPort: 443,

0 commit comments

Comments
 (0)