𝚒𝚗𝚝𝚎𝚐𝚛𝚒𝚏𝚢
🤝 Enforce referential and data integrity in Cloud Firestore using triggers
Introductory blog post
Usage
const { integrify } = require('integrify');
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
integrify({ config: { functions, db } });
module.exports.replicateMasterToDetail = integrify({
rule: 'REPLICATE_ATTRIBUTES',
source: {
collection: 'master',
},
targets: [
{
collection: 'detail1',
foreignKey: 'masterId',
attributeMapping: {
masterField1: 'detail1Field1',
masterField2: 'detail1Field2',
},
},
{
collection: 'detail2',
foreignKey: 'masterId',
attributeMapping: {
masterField1: 'detail2Field1',
masterField3: 'detail2Field3',
},
isCollectionGroup: true,
},
],
hooks: {
pre: (change, context) => {
},
},
});
module.exports.deleteReferencesToMaster = integrify({
rule: 'DELETE_REFERENCES',
source: {
collection: 'master',
},
targets: [
{
collection: 'detail1',
foreignKey: 'masterId',
isCollectionGroup: true,
},
],
hooks: {
pre: (snap, context) => {
},
},
});
[
module.exports.incrementFavoritesCount,
module.exports.decrementFavoritesCount,
] = integrify({
rule: 'MAINTAIN_COUNT',
source: {
collection: 'favorites',
foreignKey: 'articleId',
},
target: {
collection: 'articles',
attribute: 'favoritesCount',
},
});
Deploy to Firebase by executing:
$ firebase deploy --only functions
Rules File
Alternately, rules can be specified in a file named integrify.rules.js
.
const { integrify } = require('integrify');
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
integrify({ config: { functions, db } });
module.exports = integrify();
module.exports = [
{
rule: 'REPLICATE_ATTRIBUTES',
name: 'replicateMasterToDetail',
},
];
Collection Groups (isCollectionGroup
)
Firestore allows searching over multiple collections (a.k.a. collection group) with the same name at any level in the database. This is called a collection group query.
Integrify allows you to replicate tracked master attributes into (optionally) collection groups linked by a foreign key using the isCollectionGroup
parameter (see above) in the REPLICATE_ATTRIBUTES
rule. Similarly, you can delete references in a collection group (instead of just a collection) using the isCollectionGroup
in the DELETE_REFERENCES
rule.
Note: You need to first create the appropriate index to be able to use Collection Group Queries. The first time you attempt to use it, Firebase will throw an error message with a link which when clicked will prompt you to create the appropriate index. For example:
The query requires a COLLECTION_GROUP_ASC index for collection detail1 and field masterId. You can create it here: https://console.firebase.google.com/project/integrify-dev/database/firestore/indexes/single_field?create_exemption=ClNwcm9qZWNxxxxxx3RlcklkEAE
For more help, see here.