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

test/mock/WS.ts   A

Complexity

Total Complexity 5
Complexity/F 0

Size

Lines of Code 42
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 34
mnd 5
bc 5
fnc 0
dl 0
loc 42
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
2
import WebSocket, { WebSocketServer } from 'ws'
3
import {noop} from 'pepka'
4
5
let server: WebSocketServer|null = null
6
7
const createServer = (port = 40510) => new Promise<WebSocketServer>((ff, rj) => {
8
  if(server) return rj('The server is already running!')
9
  server = new WebSocketServer({ port }, () => {
10
    server!.on('connection', (socket: WebSocket&{isAlive: boolean}) => {
11
      socket.on('message', (rawMessage: string) => {
12
        const {id, data} = JSON.parse(rawMessage)
13
        let response = ''
14
        if(data.shut) {
15
          socket.terminate()
16
          socket.isAlive = false
17
          socket.ping('', false, noop)
18
          return null
19
        } else if(data.echo) {
20
          response = data
21
        }
22
        socket.send(JSON.stringify({ id, data: response }))
23
        return null
24
      })
25
      return true
26
    })
27
    return ff(server!)
28
  })
29
  server.on('', console.log)
30
})
31
32
const killServer = async () => new Promise<void>((ff, rj) => {
33
  if(server) {
34
    for(const socket of server.clients) socket.terminate()
35
    server.close(() => {
36
      server = null
37
      ff()
38
    })
39
  } else
40
    rj('The server is already down!')
41
  })
42
43
export { createServer, killServer }