firebase / firebase/firebase-admin-node
[FR] Blocking function for firestore document modification at create/update/delete
- Langage dominant
- TypeScript
- Étoiles
- 1.7k
- Forks
- 419
- Merge moyen
- 3 j 10 h
- PR mergées (30 j)
- 16
Description
**Is your feature request related to a problem? Please describe.**
There are many situation that we just not only want to protect document from being written (which could be done by security rules), but to also inject data into document or modified something complicate or written data by some logic on the server
For example, user might modified some field about their profile, such as their name or email. And then we decide that we want to index all their named profile into array of lowercase text chunks. So we could do text search with firestore `in` query
But utilizing `onWrite` function to written complicate checking logic and update same document 2 times every time user change their profile is not ideal. Especially it was admittedly risking infinite loop
**Describe the solution you'd like**
Taken idea from firebase auth blocking function, firestore should also have blocking function, `beforeWrite` function that provide the same parameter as `onWrite` function but need to return document, or throw exception to cancel writing document
Taken example from https://firebase.google.com/docs/firestore/extend-with-functions#reading_and_writing_data
```js
// Listen for updates to any `user` document.
exports.countNameChanges = functions.firestore.document('users/{userId}').onUpdate((change, context) => {
// Retrieve the current and previous value
const data = change.after.data();
const previousData = change.before.data();
// We'll only update if the name has changed.
// This is crucial to prevent infinite loops.
if (data.name == previousData.name) {
return null;
}
// Retrieve the current count of name changes
let count = data.name_change_count;
if (!count) {
count = 0;
}
// Then return a promise of a set operation to update the count
return change.after.ref.set({
name_change_count: count + 1
}, {merge: true});
});
```
Could be changed into
```js
// Listen for updates to any `user` document.
exports.countNameChanges = functions.firestore.document('users/{userId}').beforeWrite((change, context) => {
// Retrieve the current and previous value
const data = change.after.data();
const previousData = change.before.data();
if (data.name != previousData.name) {
data.name_change_count = (previousData.name_change_count || 0) + 1;
}
data.lastUpdate = FieldValue.serverTimestamp(); // now we can also index updateTime without exposing metadata updateTime
// Must return the data
return data;
});
```
**Describe alternatives you've considered**
Alternatively this could be done by the security rule directly if we have security rule v3 with more syntax to allow set feature
**Additional context**
I have not sure if it (and should it) allow blocking function in firestore with async function and transaction. Maybe it should be sync function but can request for dependency document
```js
// Listen for updates to any `user` document.
exports.countNameChanges = functions.firestore.document('users/{userId}')
.requireDocs((userId) => ["userAdditionalProfiles/" + userId,"admins/" + userId]) // array of `collection/docId` to request some documents from other collections
.beforeWrite((change, context,[profile,admin]) => {
// Retrieve the current and previous value
const data = change.after.data();
const previousData = change.before.data();
if (data.name != previousData.name) {
data.name_change_count = (previousData.name_change_count || 0) + 1;
}
if(admin.exist && data.adminLevel != admin.get("level")) {
data.adminLevel = admin.get("level"); // always sync user with admin level for indexing and querying
}
// Must return the data in sync
return data;
});
```
Or maybe providing transaction to write multiple document too?
Guide de contribution
Ouvrir le guide de contribution
Piste de recherche
L’issue mentionne les triggers de documents Firestore, les API onWrite et beforeWrite proposées, ainsi que la documentation Firebase Functions, mais ne contient aucun fichier du dépôt ni test. Commencez par examiner les points d’entrée existants des triggers Firestore et la documentation liée, puis clarifiez la prise en charge de create/update/delete, du travail asynchrone, des transactions et de l’annulation. Le travail est terminé lorsque le périmètre de l’API et les critères d’acceptation sont convenus.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Évaluation
- Stack technique
- firebase, javascript
- Domaine
- backend, databases
- Type d'issue
- Fonctionnalité
- Difficulté
- 5/5
- Temps estimé
- Plus d'une semaine
- Activité
- À l'abandon
- Clarté
- À clarifier
- Accessibilité débutants
- 25/100