index.ts 1.96 KB
Newer Older
1
2
3
4
5
import protocol from './lib/protocol.js'
import sequence from './lib/sequence.js';
import db from './lib/db.js';
import { AuditRecord,FS_ERROR } from './interfaces/index.js';
import FileEngine from './lib/FileEngine.js';
6

7
8
9
10
11
12
13
/**
 * @description Use this on your app to generate and log the audit record
 * @coment This is the main function of the application
 * @comment The audit record is stored in the database,
 * @comment you can provide a custom audit record, or use the generated one
 * @param auditInit - The audit record to be stored, if is empty a new one will be generated
 * @param storagePath - The path where the audit record will be stored, default is the tmp directory
Panagiotis Skarvelis's avatar
cleanup    
Panagiotis Skarvelis committed
14
15
 * @env env.HOSTIP - useful to pass the IP address of the end user automatically on docker enviroments
 * @returns AuditRecord | null - The audit record generated or the one provided
16
 */
Panagiotis Skarvelis's avatar
cleanup    
Panagiotis Skarvelis committed
17
export const generateAuditRecord = (auditInit: AuditRecord | undefined, storagePath: string = "/tmp"): AuditRecord | null => {
Panagiotis Skarvelis's avatar
Panagiotis Skarvelis committed
18
    const auditUnit = auditInit?.auditUnit || "gov.gr";
Panagiotis Skarvelis's avatar
cleanup    
Panagiotis Skarvelis committed
19
20
21
    const auditTransactionId = auditInit?.auditTransactionId || "" + sequence(storagePath + "/sequence", storagePath + "/sequence");
    const auditProtocol = auditInit?.auditProtocol || protocol(storagePath);
    const auditTransactionDate = auditInit?.auditTransactionDate || new Date().toISOString().split('.')[0] + "Z"
Panagiotis Skarvelis's avatar
Panagiotis Skarvelis committed
22
23
    const auditUserIp = auditInit?.auditUserIp || process.env.HOSTIP || "127.0.0.1";
    const auditUserId = auditInit?.auditUserId || "system";
24
    const auditRecord = {
Panagiotis Skarvelis's avatar
Panagiotis Skarvelis committed
25
26
27
28
29
30
31
        auditUnit,
        auditTransactionId,
        auditProtocol,
        auditTransactionDate,
        auditUserIp,
        auditUserId
    }
32
    const dbEngine = new db(new FileEngine(storagePath));
Panagiotis Skarvelis's avatar
cleanup    
Panagiotis Skarvelis committed
33
34
35
36
37
38
39
40
    try {
        return dbEngine.put(auditRecord);
    } catch (error) {
        const err = error as FS_ERROR;
        console.log(err.code,err.message);
        return null;
    }
    
41
}
42

Panagiotis Skarvelis's avatar
Panagiotis Skarvelis committed
43
export default generateAuditRecord;
Panagiotis Skarvelis's avatar
Panagiotis Skarvelis committed
44
export { AuditRecord };