Add delete expired logs methods and add the cron

This commit is contained in:
Fernando Chavez 2022-12-30 11:02:41 +01:00
parent 477cd21eba
commit 6f975b3815
4 changed files with 35 additions and 0 deletions

View File

@ -53,6 +53,7 @@ describe('Audit logs service', () => {
};
}
});
const mockScheduleJob = jest.fn();
const strapi = {
admin: {
@ -102,6 +103,11 @@ describe('Audit logs service', () => {
findMany: mockFindMany,
}),
}));
jest.mock('node-schedule', () => {
return {
scheduleJob: mockScheduleJob,
};
});
});
afterEach(() => {
@ -194,5 +200,13 @@ describe('Audit logs service', () => {
});
expect(result).toEqual({ id: 1, user: null });
});
it('should create a cron job that executed one time a day', async () => {
const auditLogsService = createAuditLogsService(strapi);
await auditLogsService.register();
expect(mockScheduleJob).toHaveBeenCalledTimes(1);
expect(mockScheduleJob).toHaveBeenCalledWith('0 0 * * *', expect.any(Function));
});
});
});

View File

@ -1,6 +1,7 @@
'use strict';
const localProvider = require('@strapi/provider-audit-logs-local');
const { scheduleJob } = require('node-schedule');
const { getService } = require('../../../server/utils');
const defaultEvents = [
@ -73,6 +74,7 @@ const createAuditLogsService = (strapi) => {
async register() {
this._provider = await localProvider.register({ strapi });
this._eventHubUnsubscribe = strapi.eventHub.subscribe(handleEvent.bind(this));
this._job = scheduleJob('0 0 * * *', () => this._provider.deleteExpiredEvents());
return this;
},
@ -111,6 +113,11 @@ const createAuditLogsService = (strapi) => {
if (this._eventHubUnsubscribe) {
this._eventHubUnsubscribe();
}
if (this._job) {
this._job.cancel();
}
return this;
},

View File

@ -105,6 +105,7 @@
"mini-css-extract-plugin": "2.4.4",
"msw": "0.49.1",
"node-polyfill-webpack-plugin": "2.0.1",
"node-schedule": "2.1.0",
"p-map": "4.0.0",
"passport-local": "1.0.0",
"prop-types": "^15.7.2",

View File

@ -2,6 +2,9 @@
const auditLogContentType = require('./content-types/audit-log');
// @TODO: Hardcoded for now, we should get this from the config later
const RETENTION_DAYS = 7;
const provider = {
async register({ strapi }) {
strapi.container.get('content-types').add('admin::', { 'audit-log': auditLogContentType });
@ -33,6 +36,16 @@ const provider = {
fields: ['action', 'date', 'payload'],
});
},
deleteExpiredEvents() {
return strapi.entityService.deleteMany('admin::audit-log', {
filters: {
date: {
$lt: new Date(Date.now() - RETENTION_DAYS * 24 * 60 * 60 * 1000).toISOString(),
},
},
});
},
};
},
};