Skip to content

Commit 611df8f

Browse files
feat(deleteReferences): Primary key is optional
1 parent dc67bc2 commit 611df8f

File tree

2 files changed

+21
-7
lines changed

2 files changed

+21
-7
lines changed

src/common.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,16 @@ function regexMatches(text: string, regex: Key): string[] {
2727
return text.match(new RegExp(regex, 'g')) || [];
2828
}
2929

30-
export function getPrimaryKey(ref: string): string {
30+
export function getPrimaryKey(
31+
ref: string
32+
): { hasPrimaryKey: boolean; primaryKey: string } {
3133
const keys = regexMatches(ref, Key.Primary);
3234
if (keys.length > 0) {
3335
const pk = keys.pop(); // Pop the last item in the matched array
34-
return pk.replace(/\{|\}/g, ''); // Remove { } from the primary key
36+
// Remove { } from the primary key
37+
return { hasPrimaryKey: true, primaryKey: pk.replace(/\{|\}/g, '') };
3538
}
36-
throw new Error('integrify: Missing a primary key in the source');
39+
return { hasPrimaryKey: false, primaryKey: 'masterId' };
3740
}
3841

3942
export function replaceReferencesWith(

src/rules/deleteReferences.ts

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,24 @@ export function integrifyDeleteReferences(
3030
)
3131
);
3232

33+
const { hasPrimaryKey, primaryKey } = getPrimaryKey(rule.source.collection);
34+
if (!hasPrimaryKey) {
35+
rule.source.collection = `${rule.source.collection}/{${primaryKey}}`;
36+
}
37+
3338
return functions.firestore
3439
.document(rule.source.collection)
3540
.onDelete((snap, context) => {
3641
// Get the last {...} in the source collection
37-
const primaryKey = context.params[getPrimaryKey(rule.source.collection)];
42+
const primaryKeyValue = context.params[primaryKey];
43+
if (!primaryKeyValue) {
44+
throw new Error(
45+
`integrify: Missing a primary key [${primaryKey}] in the source params`
46+
);
47+
}
48+
3849
console.log(
39-
`integrify: Detected delete in [${rule.source.collection}], id [${primaryKey}]`
50+
`integrify: Detected delete in [${rule.source.collection}], id [${primaryKeyValue}]`
4051
);
4152

4253
// Call "pre" hook if defined
@@ -54,7 +65,7 @@ export function integrifyDeleteReferences(
5465
target.isCollectionGroup ? 'group ' : ''
5566
}[${target.collection}] where foreign key [${
5667
target.foreignKey
57-
}] matches [${primaryKey}]`
68+
}] matches [${primaryKeyValue}]`
5869
);
5970

6071
// Replace the context.params in the target collection
@@ -80,7 +91,7 @@ export function integrifyDeleteReferences(
8091

8192
promises.push(
8293
whereable
83-
.where(target.foreignKey, '==', primaryKey)
94+
.where(target.foreignKey, '==', primaryKeyValue)
8495
.get()
8596
.then(querySnap => {
8697
querySnap.forEach(doc => {

0 commit comments

Comments
 (0)