Remove orphans task
This commit is contained in:
parent
b5db9334c8
commit
2282dc2a14
8 changed files with 75 additions and 2 deletions
|
|
@ -1,6 +1,10 @@
|
|||
const dayjs = require('dayjs');
|
||||
|
||||
module.exports = async (req, res) => {
|
||||
if (req.header('X-Appengine-Cron') === undefined) {
|
||||
return res.status(400).send('This task can only be run from a cron job');
|
||||
}
|
||||
|
||||
const threeMonthsAgo = dayjs().subtract(3, 'month').unix();
|
||||
|
||||
console.log(`Running cleanup task at ${dayjs().format('h:mma D MMM YYYY')}`);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
const dayjs = require('dayjs');
|
||||
|
||||
module.exports = async (req, res) => {
|
||||
if (req.header('X-Appengine-Cron') === undefined) {
|
||||
return res.status(400).send('This task can only be run from a cron job');
|
||||
}
|
||||
|
||||
const threeMonthsAgo = dayjs().subtract(3, 'month').unix();
|
||||
|
||||
console.log(`Running LEGACY cleanup task at ${dayjs().format('h:mma D MMM YYYY')}`);
|
||||
|
|
|
|||
46
crabfit-backend/routes/taskRemoveOrphans.js
Normal file
46
crabfit-backend/routes/taskRemoveOrphans.js
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
const dayjs = require('dayjs');
|
||||
|
||||
module.exports = async (req, res) => {
|
||||
if (req.header('X-Appengine-Cron') === undefined) {
|
||||
return res.status(400).send('This task can only be run from a cron job');
|
||||
}
|
||||
|
||||
const threeMonthsAgo = dayjs().subtract(3, 'month').unix();
|
||||
|
||||
console.log(`Running orphan removal task at ${dayjs().format('h:mma D MMM YYYY')}`);
|
||||
|
||||
try {
|
||||
// Fetch people that are older than 3 months
|
||||
const peopleQuery = req.datastore.createQuery(req.types.person).filter('created', '<', threeMonthsAgo);
|
||||
let oldPeople = (await req.datastore.runQuery(peopleQuery))[0];
|
||||
|
||||
if (oldPeople && oldPeople.length > 0) {
|
||||
console.log(`Found ${oldPeople.length} people older than 3 months, checking for events`);
|
||||
|
||||
// Fetch events linked to the people discovered
|
||||
let peopleWithoutEvents = 0;
|
||||
await Promise.all(oldPeople.map(async (person) => {
|
||||
let event = (await req.datastore.get(req.datastore.key([req.types.event, person.eventId])))[0];
|
||||
|
||||
if (!event) {
|
||||
peopleWithoutEvents++;
|
||||
await req.datastore.delete(person[req.datastore.KEY]);
|
||||
}
|
||||
}));
|
||||
|
||||
if (peopleWithoutEvents > 0) {
|
||||
console.log(`Orphan removal successful: ${oldEventIds.length} events and ${peopleDiscovered} people removed`);
|
||||
res.sendStatus(200);
|
||||
} else {
|
||||
console.log(`Found 0 people without events, ending orphan removal`);
|
||||
res.sendStatus(404);
|
||||
}
|
||||
} else {
|
||||
console.log(`Found 0 people older than 3 months, ending orphan removal`);
|
||||
res.sendStatus(404);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
res.sendStatus(404);
|
||||
}
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue