This repository has been archived on 2022-08-14. You can view files and clone it, but cannot push or open issues or pull requests.
outline/server/api/utils.js
Tom Moor 09dea295a2
fix: Cleanup S3 Attachments (#1217)
* fix: Server error if attempting to load an unknown attachment

* fix: Migration should cascade delete to document attachments

* fix: Delete S3 attachments along with documents
2020-03-28 15:56:01 -07:00

52 lines
1.1 KiB
JavaScript

// @flow
import debug from 'debug';
import Router from 'koa-router';
import subDays from 'date-fns/sub_days';
import { AuthenticationError } from '../errors';
import { Document, Attachment } from '../models';
import { Op } from '../sequelize';
const router = new Router();
const log = debug('utils');
router.post('utils.gc', async ctx => {
const { token } = ctx.body;
if (process.env.UTILS_SECRET !== token) {
throw new AuthenticationError('Invalid secret token');
}
log('Permanently deleting documents older than 30 days…');
const where = {
deletedAt: {
[Op.lt]: subDays(new Date(), 30),
},
};
const documents = await Document.scope('withUnpublished').findAll({
attributes: ['id'],
where,
});
const documentIds = documents.map(d => d.id);
await Attachment.destroy({
where: {
documentId: documentIds,
},
});
await Document.scope('withUnpublished').destroy({
where,
force: true,
});
log(`Deleted ${documentIds.length} documents`);
ctx.body = {
success: true,
};
});
export default router;