-
Notifications
You must be signed in to change notification settings - Fork 1
/
uuid-util.js
47 lines (40 loc) · 918 Bytes
/
uuid-util.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
const uid = require("uuid");
const { Binary } = require("bson");
function toBinaryUUID(uuid) {
if (uuid && typeof uuid === "string") {
const normalize = uuid.replace(/-/g, "");
const buffer = Buffer.from(normalize, "hex");
const binary = new Binary(buffer, Binary.SUBTYPE_UUID);
binary.toString = () => {
return toStringUUID(binary);
};
return binary;
}
return uuid;
}
function toStringUUID(binary) {
if (binary) {
const { buffer } = binary;
return [
buffer.toString("hex", 0, 4),
buffer.toString("hex", 4, 6),
buffer.toString("hex", 6, 8),
buffer.toString("hex", 8, 10),
buffer.toString("hex", 10, 16)
].join("-");
}
}
function v4() {
const uuid = uid.v4();
return toBinaryUUID(uuid);
}
function v1() {
const uuid = uid.v1();
return toBinaryUUID(uuid);
}
module.exports = {
toBinaryUUID,
toStringUUID,
v1,
v4
};