Skip to content

Commit 091f54e

Browse files
feat(replicateAttributes): Add optional primary key
1 parent 0c7494c commit 091f54e

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

src/rules/replicateAttributes.ts

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Config, Rule } from '../common';
1+
import { Config, Rule, getPrimaryKey } from '../common';
22
import { firestore } from 'firebase-admin';
33
const FieldValue = firestore.FieldValue;
44

@@ -43,6 +43,11 @@ export function integrifyReplicateAttributes(
4343
});
4444
});
4545

46+
const { hasPrimaryKey, primaryKey } = getPrimaryKey(rule.source.collection);
47+
if (!hasPrimaryKey) {
48+
rule.source.collection = `${rule.source.collection}/{${primaryKey}}`;
49+
}
50+
4651
// Create map of master attributes to track for replication
4752
const trackedMasterAttributes = {};
4853
rule.targets.forEach(target => {
@@ -52,12 +57,18 @@ export function integrifyReplicateAttributes(
5257
});
5358

5459
return functions.firestore
55-
.document(`${rule.source.collection}/{masterId}`)
60+
.document(rule.source.collection)
5661
.onUpdate((change, context) => {
57-
const masterId = context.params.masterId;
62+
// Get the last {...} in the source collection
63+
const primaryKeyValue = context.params[primaryKey];
64+
if (!primaryKeyValue) {
65+
throw new Error(
66+
`integrify: Missing a primary key [${primaryKey}] in the source params`
67+
);
68+
}
5869
const newValue = change.after.data();
5970
console.log(
60-
`integrify: Detected update in [${rule.source.collection}], id [${masterId}], new value:`,
71+
`integrify: Detected update in [${rule.source.collection}], id [${primaryKeyValue}], new value:`,
6172
newValue
6273
);
6374

@@ -124,7 +135,7 @@ export function integrifyReplicateAttributes(
124135
}
125136
promises.push(
126137
whereable
127-
.where(target.foreignKey, '==', masterId)
138+
.where(target.foreignKey, '==', primaryKeyValue)
128139
.get()
129140
.then(detailDocs => {
130141
detailDocs.forEach(detailDoc => {

0 commit comments

Comments
 (0)