-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
66 lines (52 loc) · 1.46 KB
/
utils.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const toHex = buff => {
if (typeof buff === 'string') {
return buff;
}
if (buff && buff.buffer) {
const str = Buffer.from(buff.buffer).toString('hex');
return Buffer.from(buff.buffer).toString('hex');
}
throw new Error('Cannot convert the buffer to hex: ', buff);
};
const toBuffer = str => {
console.log('toBuffer', str);
if (Buffer.isBuffer(str)) {
return str;
}
if (typeof str === 'string') {
const buff = Buffer.from(str, 'hex');
console.log('toBuffer str', str);
console.log('toBuffer buff', Buffer.from(str, 'hex'));
return buff;
}
throw new Error('Cannot convert the string to buffer: ', str);
};
class SwarmError extends Error {
constructor(message, code, stack) {
super(message);
this.code = code || message;
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = stack || new Error(this.message).stack;
}
}
}
const callbackPromise = () => {
let callback;
const promise = new Promise((resolve, reject) => {
callback = (err, value) => {
if (err) reject(err);
else resolve(value);
};
});
callback.promise = promise;
return callback;
};
const resolveCallback = (promise, cb) => {
if (!promise.then) {
promise = Promise.resolve();
}
return promise.then(result => cb(null, result)).catch(cb);
};
module.exports = { toHex, toBuffer, SwarmError, callbackPromise, resolveCallback };