I used 'firebase functions' to create a schedule function that periodically calls and deletes files in storage when they are old. I want to compare the file's 'timeCreated' with the current time and make it delete after 10 minutes more since the file was created. The following is part of my code.
functions/index.js
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const firebase = admin.initializeApp();
exports.scheduledFunction = functions
.region("asia-northeast3")
.pubsub.schedule("every 1 minutes")
.onRun(async (context) => {
try {
const bucket = firebase.storage().bucket();
// get files
const [filesArray] = await bucket.getFiles({
prefix: "chat/files", // storage file path
});
const TIMESTAMP_AGO = Date.now() - 600000; // before 10min
const DELETE_OPTIONS = { ignoreNotFound: true }; // ??
.
.
filesArray.map(async (file) => {
let metadata;
try {
// metadata
[metadata] = await file.getMetadata();
const { temporaryHold, eventBasedHold, timeCreated } = metadata;
const dispose = timeCreated < TIMESTAMP_AGO; // is file older check
if (dispose) {
await file.delete(DELETE_OPTIONS);
console.log("delete file");
}
}
}
}
I would like to check if the creation time is more than 10 minutes by comparing the time below. However, 'dispose' is always returned as false.
const TIMESTAMP_AGO = Date.now() - 600000;
const dispose = timeCreated < TIMESTAMP_AGO; // always false
The following is the log output from the firebase functions console.
timeCreated: 2022-05-10T14:46:08.014Z, TIMESTAMP_AGO: 1652196423265
What should I do to compare the time correctly?
The problem is that you are trying to compare datetime with timestamp.
A solution would be to turn the TIMESTAMP_AGO TO dataTime:
const TIMESTAMP_AGO = Date.now() - 600000;
const time_10mins_ago = new Date(TIMESTAMP_AGO);
const dispose = timeCreated < time_10mins_ago;