-
Notifications
You must be signed in to change notification settings - Fork 0
/
dpk.js
39 lines (28 loc) · 874 Bytes
/
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
const crypto = require("crypto");
const TRIVIAL_PARTITION_KEY = "0";
const MAX_PARTITION_KEY_LENGTH = 256;
const DIGEST_STRING = 'hex';
function generateDigestCryptoHash(hash, data) {
return hash.update(data).digest(DIGEST_STRING);
}
module.exports.deterministicPartitionKey = (input) => {
if(!input) return TRIVIAL_PARTITION_KEY;
const hash = crypto.createHash('sha3-512');
let candidate;
if (input.partitionKey) {
candidate = input.partitionKey;
} else {
const data = JSON.stringify(input);
candidate = generateDigestCryptoHash(hash, data);
}
if(!candidate) {
return TRIVIAL_PARTITION_KEY;
}
if (typeof candidate !== 'string') {
candidate = JSON.stringify(candidate);
}
if (candidate.length > MAX_PARTITION_KEY_LENGTH) {
candidate = generateDigestCryptoHash(hash, candidate);
}
return candidate;
};