-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
44 lines (36 loc) · 1.08 KB
/
index.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
const util = require('util')
const tr = require('./binding')
class Transmission {
constructor (configDir = 'transmission', appName = 'transmission') {
// Keep reference of requests in a set to avoid the requests to be GC
this.set = new Set()
// NOTE: we append the buffer with a null character to delimitate the C string
tr.sessionInit(Buffer.from(configDir + '\0'), Buffer.from(appName + '\0'))
}
close () {
tr.sessionClose()
}
request (reqJson, cb) {
// Callback api
if (cb && typeof cb === 'function') {
return this._request(reqJson, cb)
}
// Promise api
const promisified = util.promisify(this._request).bind(this)
return promisified(reqJson)
}
_request (reqJson, cb) {
const self = Buffer.alloc(tr.sizeof_tr_napi_t)
this.set.add(self)
tr.request(self, Buffer.from(JSON.stringify(reqJson)), (err, res) => {
if (err) return cb(err)
const resJson = JSON.parse(res)
this.set.delete(self)
cb(null, resJson)
})
}
saveSettings () {
tr.saveSettings()
}
}
module.exports = Transmission