-
Notifications
You must be signed in to change notification settings - Fork 0
/
dpk.js
executable file
·55 lines (45 loc) · 1.37 KB
/
dpk.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
const crypto = require("crypto");
// before refactor
exports.deterministicPartitionKey_before = (event) => {
const TRIVIAL_PARTITION_KEY = "0";
const MAX_PARTITION_KEY_LENGTH = 256;
let candidate;
if (event) {
if (event.partitionKey) {
candidate = event.partitionKey;
} else {
const data = JSON.stringify(event);
candidate = crypto.createHash("sha3-512").update(data).digest("hex");
}
}
if (candidate) {
if (typeof candidate !== "string") {
candidate = JSON.stringify(candidate);
}
} else {
candidate = TRIVIAL_PARTITION_KEY;
}
if (candidate.length > MAX_PARTITION_KEY_LENGTH) {
candidate = crypto.createHash("sha3-512").update(candidate).digest("hex");
}
return candidate;
};
// after refactor
exports.deterministicPartitionKey = (event) => {
const TRIVIAL_PARTITION_KEY = "0";
const MAX_PARTITION_KEY_LENGTH = 256;
let candidate = TRIVIAL_PARTITION_KEY;
if (event && event.partitionKey) {
candidate = event.partitionKey;
} else if (event) {
const data = JSON.stringify(event);
candidate = crypto.createHash("sha3-512").update(data).digest("hex");
}
if (typeof candidate !== "string") {
candidate = JSON.stringify(candidate);
}
if (candidate.length > MAX_PARTITION_KEY_LENGTH) {
candidate = crypto.createHash("sha3-512").update(candidate).digest("hex");
}
return candidate;
};