Replies: 2 comments
-
Here's an example universal timestamp trigger I wrote. import * as functions from "firebase-functions";
import * as equal from "fast-deep-equal";
module.exports = functions
.runWith({
memory: "128MB",
})
.firestore.document(`{col0}/{doc0}/{col1}/{doc1}`)
.onWrite(async (change, context) => {
/**
* Takes an array of short collection paths
* A short collection path are collections paths with the document omitted
* Example:
* Normal: /users/{userId}/posts/{postId}
* Short: /users/posts
*/
const targets = ["projects/comments", "users/clubs"];
let counter = 0;
let collections = [];
// Build short collection path
for (let key in context.params) {
// Skip document values
if (key.startsWith("doc")) {
continue;
}
collections.push(context.params[`col${counter}`]);
counter++;
}
functions.logger.debug(context.params);
if (!targets.includes(collections.join("/"))) {
functions.logger.debug(
`Collection not targeted, ignoring: ${change.before.ref.path}`
);
return Promise.resolve();
}
const timestamp = new Date();
if (!change.before.exists) {
return change.after.ref.update({
createdAt: timestamp,
updatedAt: timestamp,
});
}
const beforeData = change.before.data();
const afterData = change.after.data();
// Underlying data didn't change, don't do anything
if (
equal(
{ ...beforeData, createdAt: 0, updatedAt: 0 },
{ ...afterData, createdAt: 0, updatedAt: 0 }
)
) {
functions.logger.debug("No data changed, no timestamp updated needed.");
return;
}
return change.after.ref.set(
{
updatedAt: timestamp,
},
{ merge: true }
);
}); |
Beta Was this translation helpful? Give feedback.
0 replies
-
@narkeeso This is an excellent suggestion in general but maybe not for
Perhaps an independent Firebase Extension might be a better suited solution for this requirement. See more details here. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
At my workplace we use Firestore triggers to maintain timestamps. Right now we just define individual trigger functions which are becoming annoying to deploy. I was thinking I'd create a single trigger that would have a wildcard document matcher to update timestamps to all whitelisted collections.
Then that got me thinking it would be cool if I could just update my Integrify definition and add an array of collections to watch for. Thoughts on timestamps being relevant for this library?
I think this could fire up a single trigger with a wildcard expression and then match document paths somehow. I think the definition syntax could use some work.
Beta Was this translation helpful? Give feedback.
All reactions