-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
73 lines (62 loc) · 2.03 KB
/
index.ts
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
import {IMetadata} from 'stripe';
// Default values from https://stripe.com/docs/api#metadata
export const MAX_KEY_LENGTH = 40;
export const MAX_NUM_KEYS = 20;
export const MAX_VALUE_LENGTH = 500;
export function formatStripeMetadata(
data: any,
options?: {
maxKeyLength?: number;
maxNumKeys?: number;
maxValueLength?: number;
}
): IMetadata {
if (data === null || typeof data === 'undefined') {
return {
_fullData: 'true'
};
}
const maxKeyLength =
options && options.maxKeyLength ? options.maxKeyLength : MAX_KEY_LENGTH;
const maxNumKeys =
options && options.maxNumKeys ? options.maxNumKeys : MAX_NUM_KEYS;
const maxValueLength =
options && options.maxValueLength
? options.maxValueLength
: MAX_VALUE_LENGTH;
if (typeof data === 'string' || typeof data === 'number') {
const dataString = data.toString();
return {
_fullData: (dataString.length <= maxValueLength).toString(),
data: dataString.substr(0, maxValueLength)
};
}
if (Array.isArray(data)) {
const dataString = JSON.stringify(data);
return {
_fullData: (dataString.length <= maxValueLength).toString(),
data: dataString.substr(0, maxValueLength)
};
}
const keys = Object.keys(data);
let fullData = keys.length <= maxNumKeys - 1;
const metadata: IMetadata = {};
for (const key of keys.slice(0, maxNumKeys - 1)) {
let newKey = key;
if (key.length > maxKeyLength) {
newKey = key.substr(0, maxKeyLength);
fullData = false;
}
let value =
typeof data[key] === 'string'
? data[key]
: JSON.stringify(data[key]);
if (value.length > maxValueLength) {
value = value.substr(0, maxValueLength);
fullData = false;
}
metadata[newKey] = value;
}
metadata._fullData = fullData.toString();
return metadata;
}