FileEngine.ts 1.37 KB
Newer Older
Panagiotis Skarvelis's avatar
Panagiotis Skarvelis committed
1
2
//Use File System as DB storage
import fs from 'fs';
3
import { AuditRecord, AuditEngine } from '../interfaces/index.js';
Panagiotis Skarvelis's avatar
Panagiotis Skarvelis committed
4
5
6
7
8
9
10
11
12

/**
 * @description AuditEngine implementation
 * @note This class is used to implement the methods that must be implemented by the AuditEngine
 * @class FileEngine
 * @implements AuditEngine
 * @param {string} path - path to store the records
 */
export class FileEngine implements AuditEngine {
Panagiotis Skarvelis's avatar
cleanup    
Panagiotis Skarvelis committed
13
14
15
16
17
  #path: string

  constructor(path: string) {
    this.#path = path;
  }
Panagiotis Skarvelis's avatar
Panagiotis Skarvelis committed
18

Panagiotis Skarvelis's avatar
cleanup    
Panagiotis Skarvelis committed
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
  /**
   * @description Store a record in the database
   * @param {AuditRecord} record - record to be stored
   * @returns {AuditRecord} - the record stored
   * @memberof FileEngine
   * @method put
   */
  put(record: AuditRecord): AuditRecord {
    const data = JSON.stringify(record, null, 2);
    try {
      fs.writeFileSync(this.#path + '/record-' + record.auditTransactionId + '.json', data);
      return record;
    } catch (error) {
      throw error;
    }
  }
  /**
   * @description Get a record from the database
   * @param auditTransactionId 
   * @returns {AuditRecord}
   * @memberof FileEngine
   * @method get
   */
  get(auditTransactionId: string): AuditRecord {
    try {
      const data = fs.readFileSync(this.#path + '/record-' + auditTransactionId + '.json', 'utf8');
      return JSON.parse(data);
    } catch (error) {
      throw error;
Panagiotis Skarvelis's avatar
Panagiotis Skarvelis committed
48
    }
Panagiotis Skarvelis's avatar
cleanup    
Panagiotis Skarvelis committed
49
  }
Panagiotis Skarvelis's avatar
Panagiotis Skarvelis committed
50
51
52
53

}

export default FileEngine;