-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.js
45 lines (39 loc) · 1.21 KB
/
client.js
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
'use strict'
const { createConnection } = require('net')
const protocol = require('./protocol')
/**
* Options:
* - port: number = 9042
* - host: string = 'localhost'
* - password: string? = null (server password)
*
* Output: Promise<EventEmitter>
*/
module.exports = (options = {}) => new Promise((resolve, reject) => {
const { port = 9042, host = 'localhost', password = null } = options
const socket = createConnection(port, host)
socket.once('connect', () => {
const proto = protocol.bindSocket(socket)
proto.once('reqAuth', authRequired => {
if (authRequired && !password) {
reject(new Error('PASSWORD_REQUIRED'))
} else if (!authRequired && password) {
reject(new Error('PASSWORD_UNEXPECTED'))
} else if (authRequired && password) {
proto.emit('password', password)
proto.once('auth', ({ authorized, error }) => {
if (authorized) {
resolve(proto)
} else {
reject(new Error(error))
}
})
} else {
// Server still expects an empty password to init events
proto.emit('password', '')
resolve(proto)
}
})
})
socket.once('error', err => reject(err))
})