-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathwebsocket.provider.ts
57 lines (50 loc) · 1.65 KB
/
websocket.provider.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import * as WebSocket from 'ws'
import { getWebSocketToken } from './websocket.utils'
import { WebSocketModuleOptions, WebSocketModuleAsyncOptions } from './websocket.interface'
import { Provider } from '@nestjs/common'
import { defer, lastValueFrom } from 'rxjs'
import { WEBSOCKET_PROVIDER_NAME, WEBSOCKET_MODULE_OPTIONS } from './websocket.constants'
async function createWebSocket(_options: WebSocketModuleOptions): Promise<WebSocket> {
try {
const { url, protocols, options } = _options
let ws: WebSocket
if (protocols) {
ws = new WebSocket(url, protocols, options)
} else {
ws = new WebSocket(url, options)
}
return ws
} catch (err) {
throw new Error(`The connection cannot be established. ${err}`)
}
}
export function createWebSocketProvider(options: WebSocketModuleOptions): Provider {
return {
provide: getWebSocketToken(),
useFactory: async (): Promise<WebSocket> => {
return await lastValueFrom(defer(() => createWebSocket(options)))
},
}
}
export function createWebSocketAsyncProvider(): Provider {
return {
provide: getWebSocketToken(),
useFactory: async (options: WebSocketModuleOptions): Promise<WebSocket> => {
return lastValueFrom(defer(() => createWebSocket(options)))
},
inject: [WEBSOCKET_MODULE_OPTIONS],
}
}
export function createAsyncOptionsProvider(options: WebSocketModuleAsyncOptions): Provider {
return {
provide: WEBSOCKET_MODULE_OPTIONS,
useFactory: options.useFactory,
inject: options.inject || [],
}
}
export function createProviderName(): Provider {
return {
provide: WEBSOCKET_PROVIDER_NAME,
useValue: getWebSocketToken(),
}
}