-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathunsafeFields.ts
More file actions
93 lines (81 loc) · 2.55 KB
/
unsafeFields.ts
File metadata and controls
93 lines (81 loc) · 2.55 KB
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
import { GroupedEventDBScheme, RepetitionDBScheme as RepetitionDBSchemeType } from '@hawk.so/types';
type RepetitionDBScheme = Omit<RepetitionDBSchemeType, 'payload'> & Partial<Pick<RepetitionDBSchemeType, 'payload'>>;
/**
* Fields in event payload with unsafe data for encoding before saving in database
*/
export const unsafeFields = ['context', 'addons'] as const;
/**
* Decodes some event fields
* Some object keys can contain dots and MongoDB will throw error on save, that's because they were encoded
*
* @param event - event to encode its fields
*/
export function decodeUnsafeFields(event: GroupedEventDBScheme | RepetitionDBScheme): void {
unsafeFields.forEach((field) => {
try {
let fieldValue: unknown;
if ('delta' in event) {
fieldValue = event.delta[field];
} else {
fieldValue = event.payload[field];
}
if (typeof fieldValue === 'string') {
if ('delta' in event) {
event.delta[field] = JSON.parse(fieldValue);
} else {
event.payload[field] = JSON.parse(fieldValue);
}
}
} catch {
console.error(`Failed to parse field ${field} in event ${event._id}`);
}
});
}
/**
* Stringifies some event fields because some object keys can contain dots and MongoDB will throw error on save
*
* @param event - event to encode its fields
*/
export function encodeUnsafeFields(event: GroupedEventDBScheme | RepetitionDBScheme): void {
unsafeFields.forEach((field) => {
let fieldValue: unknown;
/**
* Repetition includes delta field, grouped event includes payload
*/
if ('delta' in event) {
/**
* We need to check if delta field exists but with undefined value
* It would mean that repetition payload is same with original event paylaod
*/
if (event.delta === undefined) {
return;
}
fieldValue = event.delta[field];
} else {
fieldValue = event.payload[field];
}
/**
* Repetition diff can omit these fields if they are not changed
*/
if (fieldValue === undefined) {
return;
}
let newValue: string;
try {
if (typeof fieldValue !== 'string') {
newValue = JSON.stringify(fieldValue);
}
} catch {
console.error(`Failed to stringify field ${field} in event ${event._id}`);
newValue = undefined;
}
/**
* Repetition includes delta field, grouped event includes payload
*/
if ('delta' in event) {
event.delta[field] = newValue;
} else {
event.payload[field] = newValue;
}
});
}