/
replicateAttributes.ts
146 lines (132 loc) 路 4.52 KB
/
replicateAttributes.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import { Change, CloudFunction } from 'firebase-functions';
import { DocumentSnapshot } from 'firebase-functions/lib/providers/firestore';
import { Config, Rule } from '../common';
export interface ReplicateAttributesRule extends Rule {
source: {
collection: string;
};
targets: {
collection: string;
foreignKey: string;
attributeMapping: {
[sourceAttribute: string]: string;
};
isCollectionGroup?: boolean;
}[];
hooks?: {
// eslint-disable-next-line @typescript-eslint/ban-types
pre?: Function;
};
}
export function isReplicateAttributesRule(
arg: Rule
): arg is ReplicateAttributesRule {
return arg.rule === 'REPLICATE_ATTRIBUTES';
}
export type ReplicateAttributesFunction = CloudFunction<
Change<DocumentSnapshot>
>;
export function integrifyReplicateAttributes(
rule: ReplicateAttributesRule,
config: Config
): ReplicateAttributesFunction {
const functions = config.config.functions;
console.log(
`integrify: Creating function to replicate source collection [${rule.source.collection}]`
);
rule.targets.forEach((target) => {
Object.keys(target.attributeMapping).forEach((sourceAttribute) => {
console.log(
`integrify: Replicating [${rule.source.collection}].[${sourceAttribute}] => [${target.collection}].[${target.attributeMapping[sourceAttribute]}]`
);
});
});
// Create map of master attributes to track for replication
const trackedMasterAttributes = {};
rule.targets.forEach((target) => {
Object.keys(target.attributeMapping).forEach((masterAttribute) => {
trackedMasterAttributes[masterAttribute] = true;
});
});
return functions.firestore
.document(`${rule.source.collection}/{masterId}`)
.onUpdate((change, context) => {
const masterId = context.params.masterId;
const newValue = change.after.data();
const oldValue = change.before.data();
console.log(
`integrify: Detected update in [${rule.source.collection}], id [${masterId}], new value:`,
newValue
);
// Call "pre" hook if defined
const promises = [];
// istanbul ignore else
if (rule.hooks && rule.hooks.pre) {
promises.push(rule.hooks.pre(change, context));
console.log(`integrify: Running pre-hook: ${rule.hooks.pre}`);
}
// Check if atleast one of the attributes to be replicated was changed
let relevantUpdate = false;
Object.keys(newValue).forEach((changedAttribute) => {
if (
trackedMasterAttributes[changedAttribute] &&
newValue[changedAttribute] !== oldValue[changedAttribute]
) {
relevantUpdate = true;
}
});
if (!relevantUpdate) {
console.log(
`integrify: No relevant updates found for replication:`,
newValue
);
return null;
}
// Loop over each target specification to replicate atributes
const db = config.config.db;
rule.targets.forEach((target) => {
const targetCollection = target.collection;
const update = {};
// Create "update" mapping each changed attribute from source => target
Object.keys(newValue).forEach((changedAttribute) => {
if (target.attributeMapping[changedAttribute]) {
update[target.attributeMapping[changedAttribute]] =
newValue[changedAttribute];
}
});
console.log(
`integrify: On collection ${
target.isCollectionGroup ? 'group ' : ''
}[${target.collection}], applying update:`,
update
);
// For each doc in targetCollection where foreignKey matches master.id,
// apply "update" computed above
let whereable = null;
if (target.isCollectionGroup) {
whereable = db.collectionGroup(targetCollection);
} else {
whereable = db.collection(targetCollection);
}
promises.push(
whereable
.where(target.foreignKey, '==', masterId)
.get()
.then((detailDocs) => {
detailDocs.forEach((detailDoc) => {
console.log(
`integrify: On collection ${
target.isCollectionGroup ? 'group ' : ''
}[${target.collection}], id [${
detailDoc.id
}], applying update:`,
update
);
promises.push(detailDoc.ref.update(update));
});
})
);
});
return Promise.all(promises);
});
}