Passed
Branch master (5df6c0)
by Michael
02:01
created

test/utils.ts   A

Complexity

Total Complexity 2
Complexity/F 0

Size

Lines of Code 26
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 2
eloc 20
mnd 2
bc 2
fnc 0
dl 0
loc 26
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
2
import {WebSocketClient} from '../src/WSC'
3
import {AnyFunc, AnyObject} from 'pepka'
4
import { native_ws } from '../src/utils'
5
import WS from 'ws'
6
7
export const createNew = (config = {}, port: number) => new WebSocketClient(Object.assign({
8
    url: 'ws://127.0.0.1:' + port,
9
    // log: (...a) => console.log(...a),
10
    adapter: (host: string, protocols?: string|string[]) => new (native_ws || WS)(host, protocols)
11
  }, config)
12
)
13
14
// Inspired by tinchoz49 https://github.com/lukeed/uvu/issues/33#issuecomment-879870292
15
export const timeout = (time: number, handler: AnyFunc) => async (context: AnyObject) => {
16
  let timer: NodeJS.Timeout
17
  try {
18
    return await Promise.race([
19
      handler(context),
20
      new Promise((_resolve, reject) =>
21
        timer = setTimeout(() => reject(new Error('timeout')), time)
22
      )
23
    ])
24
  } finally {
25
    if(timer!) clearTimeout(timer)
26
  }
27
}