Reputation: 839
I want to check documents as they are created in firestore to ensure there are no swear words contained in a publicly visible field. I would like to be able to delete the post after it has been detected to contain swear words. To do this I am trying to use firebase cloud functions:
// Package used to filter profanity
const badWordsFilter = require('bad words-list');
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Cloud Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
export const filterBadWords =
functions.firestore.document("posts/{userId}/userPosts/{postId}").onCreate((snapshot, context) => {
const message = snapshot.data.val();
// Check if post contains bad word
if (containsSwearwords(message)) {
//This is where I want to remove the post.
//What do I put here to delete the document?
}
})
// Returns true if the string contains swearwords.
function containsSwearwords(message: any) {
return message !== badWordsFilter.clean(message);
}
Database structure:
-posts(Collection)
|
+---{userID} (Document)
|
+---userPosts (collection)
|
+---{Documents to be checked} (Document)
|
+-Url1(field)
+-Url2(field)
+-string1(field)<- check this field for swear
+-string2(field)<- check this field for swear
The cloud functions are written using javascript
Upvotes: 4
Views: 2229
Reputation: 346
This answer is going to be short, but it doesn't require an explanation. Here's the code (for swift, I'm not 100% sure how to do this in js)
swift:
db.collection("cities").document("DC").delete() { err in
if let err = err {
print("Error removing document: \(err)")
} else {
print("Document successfully removed!")
}
}
this might work for javascript, not 100% sure
db.collection("cities").doc("DC").delete().then(function() {
console.log("Document successfully deleted!");
}).catch(function(error) {
console.error("Error removing document: ", error);
});
hope it helps
Upvotes: 0
Reputation: 71891
You can just use the ref
to get the DocumentReference
and call delete()
:
functions.firestore.document("posts/{userId}/userPosts/{postId}").onCreate(
async (snapshot, context) => {
const message = snapshot.data.val();
// Check if post contains bad word
if (containsSwearwords(message)) {
await snapshot.ref.delete();
}
}
)
If they can edit their post afterwards, you should generalize this functionality and add it to the onUpdate
trigger as well
Upvotes: 2