-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
102 lines (94 loc) · 2.71 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
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
'use strict';
const shardUUID = require('./build/Release/shard-uuid.node');
const Long = require('long');
const is = require('is_js');
/**
* UUID (64bits) = timestamp (32 bits) | shardId (22 bits) | localId (10 bits)
*/
/**
* Convert buffer to Long
* @param buffer
* @returns {Long|undefined}
*/
function bufferToLong (buffer) {
return buffer ? new Long(buffer.readInt32LE(0), buffer.readInt32LE(4), true) : undefined;
}
module.exports = {
/**
* Generate UUID
* @param shardId
* @param localId
* @param timestamp
* @returns {Promise}
*/
getUUID (shardId, localId, timestamp) {
return new Promise((resolve, reject) => {
let buffer = shardUUID.getUUID(shardId, localId, timestamp);
if (is.existy(buffer)) {
let uuid = bufferToLong(buffer);
if (is.existy(uuid) && Long.isLong(uuid)) {
resolve(uuid.toString());
} else {
reject(new Error('UUID error: buffer conversion'));
}
} else {
reject(new Error('UUID error: empty buffer'));
}
});
},
/**
* Get time from UUID
* @param uuid
* @returns {Promise}
*/
getTime (uuid) {
return new Promise((resolve, reject) => {
let time = shardUUID.getTime(uuid);
if (is.existy(time) && is.number(time)) {
resolve(time);
} else {
reject(new Error('UUID error: invalid time'));
}
});
},
/**
* Get shard id from UUID
* @param uuid
* @returns {Promise}
*/
getShardId (uuid) {
return new Promise((resolve, reject) => {
let shardId = shardUUID.getShardId(uuid);
if (is.existy(shardId) && is.number(shardId)) {
resolve(shardId);
} else {
reject(new Error('UUID error: invalid shard id'));
}
});
},
/**
* Get local id from UUID
* @param uuid
* @returns {Promise}
*/
getLocalId (uuid) {
return new Promise((resolve, reject) => {
let localId = shardUUID.getLocalId(uuid);
if (is.existy(localId) && is.number(localId)) {
resolve(localId);
} else {
reject(new Error('UUID error: invalid local id'));
}
});
},
getInfo (uuid) {
return new Promise((resolve, reject) => {
let info = shardUUID.getInfo(uuid);
if (is.existy(info) && is.object(info)) {
resolve(info);
} else {
reject(new Error('UUID error: invalid info'));
}
});
}
};