All files / services AuditLogsService.js

69.35% Statements 43/62
87.5% Branches 7/8
71.42% Functions 5/7
69.35% Lines 43/62

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 631x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x                             1x  
import dayjs from 'dayjs';
import {DEFAULT_TZ} from "../lib/Common.js";
 
class AuditLogsSingleton {
    constructor() {
        this.auditLogs = [];// in memory audit logs
    }
 
    static get() {
        if (!AuditLogsSingleton.instance) {
            AuditLogsSingleton.instance = new AuditLogsSingleton();
        }
        return AuditLogsSingleton.instance;
    }
}
 
export default class AuditLogsService {
 
    constructor(discordService) {
        this.discordService = discordService;
    }
 
    createAuditLog(log) {
        const instant = dayjs(new Date()).tz(DEFAULT_TZ).format("DD/MM/YYYY à HH:mm");
        AuditLogsSingleton.get().auditLogs.push({instant, log})
    }
 
    retrieveAuditLogs(cleanup = false) {
        const logs = AuditLogsSingleton.get().auditLogs;
        const clone = [].concat(logs);
        if (true === cleanup) {
            AuditLogsSingleton.get().auditLogs = [];
        }
        return clone;
    }
 
    async notifyLogs() {
        const logs = this.retrieveAuditLogs(true);
        console.log(`*${logs?.length}`);// debug
        if (logs === undefined || logs.length < 1) {
            return;
        }
        let markdown = this.formatMarkdownMessageFromLogs(logs);
        return await this.discordService.sendMessage(markdown);
    }
 
    formatMarkdownMessageFromLogs(logs) {
        const count = logs.length;
        const nbMsg = count > 1 ? `${count} messages` : `${count} message`;
        let markdown = `${nbMsg} :\n` + "```\n";
        markdown += logs.map(entry => `${entry.instant}|${entry.log}`).join(" \n");
        markdown += "\n```";

        //~ prevent discord limit
        const MAX_DISCORD_MSG_LENGTH = 2000;
        if (markdown.length > MAX_DISCORD_MSG_LENGTH) {
            markdown = markdown.substring(0, MAX_DISCORD_MSG_LENGTH - 12);
            markdown += "\n(...)\n```";
        }
        return markdown;
    }
}