-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUtils.js
85 lines (71 loc) · 1.95 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
'use strict';
/**
*
* @param {*} str -
* @param {*} structType -
*
* @returns {false | Object | Array }
*/
function isJsonStruct(str, structType) {
if (typeof str !== 'string') {
return false;
}
try {
const result = JSON.parse(str);
const type = Object.prototype.toString.call(result);
return (type === `[object ${structType}]`) ? result : false;
} catch (err) {
return false;
}
}
class Utils {
/**
* Converts `obj` into a Buffer
* @param {*} obj
* @returns {Buffer}
*/
static serialize(obj) {
return Buffer.from(JSON.stringify(obj));
}
/**
* Converts a Buffer into it's original form
* @param {Buffer} buf
* @returns {*}
*/
static deserialize(buf) {
return JSON.parse(buf.toString());
}
static isEmpty(buf) {
if (!buf) {
return true;
}
return (Buffer.isBuffer(buf) && buf.length === 0);
}
static getJourneyKey({ droneId, owner, type, status }) {
return { droneId, owner, type, status };
}
static validateJourneyKey(state) {
const allValidKeys = ['droneId', 'owner', 'type', 'status'];
const stateKeys = Object.keys(state);
// Check attribute's presence
allValidKeys.forEach(key => {
if (!stateKeys.includes(key)) {
throw Error(`The state attribute (${key}) couldn't be found`);
}
});
// Check attribute value's type
stateKeys.forEach(key => {
const val = state[key];
if (!val || typeof val !== 'string' || val.trim().length === 0) {
throw new TypeError(`Can't create a key with a non-string attribute (${key}:${val})`);
}
});
}
static isJsonObj(str) {
return isJsonStruct(str, 'Object');
}
static isJsonArr(str) {
return isJsonStruct(str, 'Array');
}
}
module.exports = Utils;