All files / src/services/file-system FileSystemService.ts

81.25% Statements 26/32
0% Branches 0/3
87.5% Functions 7/8
80.65% Lines 25/31
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 63  2x 2x 2x 2x 2x 2x 2x     1x 1x     2x 8x 2x 2x     8x 8x     1x 1x 1x     1x 1x 1x                       1x 1x 1x     2x                            
import { promisify } from 'util';
import { readdir, readFile, writeFile } from 'fs';
import { join, sep } from 'path';
import { FileListSanitizeStrategy } from './FileListSanitizeStrategy';
 
const readdirAsync = promisify(readdir);
const readFileAsync = promisify(readFile);
const writeFileAsync = promisify(writeFile);
 
 
export class FileSystemService {
 
  private backupSufix = 'i18n-manager_backup_file';
 
  constructor(private sStrategy: FileListSanitizeStrategy) {}
 
  async getFiles(path: string): Promise<Array<string>> {
    const files = await readdirAsync(path);
    const filesWithPath = files.map((file: string) => join(path, file));
    const sanitized = this.sStrategy.sanitize(filesWithPath);
 
    return sanitized;
  }
 
  getFileName(path: string): string {
    const parts = path.split(sep);
    return parts[parts.length -1];
  }
 
  async getFileNames(path: string): Promise<Array<string>> {
    const files = await this.getFiles(path);
    const names = files.map(this.getFileName);
 
    return names;
  }

  async getFileContentAsObj(path: string): Promise<Object> {
    const fileContent = await readFileAsync(path);
    const asObj = JSON.parse(fileContent);

    return asObj;
  }
 
  async saveContentToFile(path: string, content: any, doBackup: boolean = true) {
    if (doBackup) {
      const backupPath = this.getBackupPath(path);
      const originalContent = await readFileAsync(path);
 
      await writeFileAsync(backupPath, originalContent);
    }
 
    const contentAsString = JSON.stringify(content, null, 2);
    await writeFile(path, contentAsString);
  }
 
  getBackupPath(path: string): string {
    const fileName = this.getFileName(path);
    const backupPath = path.replace(fileName, `${fileName}_${this.backupSufix}`);
 
    return backupPath;
  }
 
}