traxxx/src/tools/alerts-save.js

72 lines
1.9 KiB
JavaScript

'use strict';
const fs = require('fs');
const moment = require('moment');
const knex = require('../knex');
async function save() {
const filename = `alerts-${moment().format('YYYY-MM-DD_hh_mm')}.json`;
const alerts = await knex('alerts')
.select([
'alerts.*',
'users.username',
'entities.slug as entity_slug',
'entities.type as entity_type',
])
.leftJoin('users', 'users.id', 'alerts.user_id')
.leftJoin('alerts_entities', 'alerts_entities.alert_id', 'alerts.id')
.leftJoin('entities', 'entities.id', 'alerts_entities.entity_id');
let savedAlerts = 0;
await alerts.reduce(async (chain, alert) => {
await chain;
const actors = await knex('alerts_actors')
.select('actors.slug', 'entities.slug as entity_slug', 'entities.type as entity_type')
.leftJoin('actors', 'actors.id', 'alerts_actors.actor_id')
.leftJoin('entities', 'entities.id', 'actors.entity_id')
.where('alert_id', alert.id);
const tags = await knex('alerts_tags')
.select('tags.slug')
.leftJoin('tags', 'tags.id', 'alerts_tags.tag_id')
.where('alert_id', alert.id);
const stashes = await knex('alerts_stashes')
.select('stashes.slug')
.leftJoin('stashes', 'stashes.id', 'alerts_stashes.stash_id')
.where('alert_id', alert.id);
const curatedAlert = {
username: alert.username,
notify: alert.notify,
email: alert.email,
createdAt: alert.created_at,
actors: actors.map((actor) => ({
slug: actor.slug,
entitySlug: actor.entity_slug,
entityType: actor.entity_type,
})),
tags: tags.map((tag) => tag.slug),
stashes: stashes.map((stash) => stash.slug),
entitySlug: alert.entity_slug,
entityType: alert.entity_type,
};
await fs.promises.appendFile(filename, `${JSON.stringify(curatedAlert)}\n`);
console.log(`Saved ${alert.username} alert`);
savedAlerts += 1;
}, Promise.resolve());
console.log(`Saved ${savedAlerts} alerts to ${filename}`);
process.exit();
}
save();