Total Complexity | 4 |
Complexity/F | 0 |
Lines of Code | 55 |
Function Count | 0 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 0 |
1 | import './types' |
||
2 | import { native_ws } from './utils' |
||
3 | |||
4 | const default_config = <wsc.Config>{ |
||
5 | data_type: 'json', // ToDo some other stuff maybe. |
||
6 | // Debug features. |
||
7 | log: (() => null), |
||
8 | timer: false, |
||
9 | // Set up. |
||
10 | url: 'localhost', |
||
11 | timeout: 1400, |
||
12 | reconnect: 2, // Reconnect timeout in seconds or null. |
||
13 | lazy: false, |
||
14 | socket: null, |
||
15 | adapter: ((host, protocols) => new WebSocket(host, protocols)), |
||
16 | encode: (key, data, { server }) => JSON.stringify({ |
||
17 | [server.id_key]: key, |
||
18 | [server.data_key]: data |
||
19 | }), |
||
20 | decode: (rawMessage) => JSON.parse(rawMessage), |
||
21 | protocols: [], |
||
22 | pipes: [], |
||
23 | server: { |
||
24 | id_key: 'id', |
||
25 | data_key: 'data' |
||
26 | }, |
||
27 | ping: { |
||
28 | interval: 55, |
||
29 | content: {} |
||
30 | } |
||
31 | } |
||
32 | |||
33 | export const processConfig = (config: wsc.UserConfig) => { |
||
34 | if(native_ws===null && !('adapter' in config)) throw new Error(` |
||
35 | This platform has no native WebSocket implementation. |
||
36 | Please use 'ws' package as an adapter. |
||
37 | See https://github.com/houd1ni/WebsocketPromisify/issues/23 |
||
38 | `) |
||
39 | const full_config: wsc.Config = Object.assign( |
||
40 | {}, |
||
41 | default_config, |
||
42 | config |
||
43 | ) |
||
44 | const url = full_config.url |
||
45 | if(url[0] == '/') { |
||
46 | try { |
||
47 | const protocol = location.protocol.includes('s:') ? 'wss' : 'ws' |
||
48 | full_config.url = `${protocol}://${location.hostname}:${location.port}${url}` |
||
49 | } catch (e) { |
||
50 | throw new Error('WSP: URL starting with / in non-browser environment!') |
||
51 | } |
||
52 | } |
||
53 | |||
54 | return full_config |
||
55 | } |