All files / common/util yaml.ts

100% Statements 26/26
100% Branches 0/0
100% Functions 3/3
100% Lines 23/23

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 488x 8x   8x 8x   8x         8x 3x 3x   2x   1x             8x 2x 2x 2x 2x   2x   1x             8x 30x 30x 30x 30x   30x    
import * as fs from 'fs/promises';
import * as path from 'path';
 
import * as YAML from 'js-yaml';
import {ERRORS} from '@grnsft/if-core/utils';
 
const {ReadFileError, WriteFileError} = ERRORS;
 
/**
 * Reads and parses `yaml` file to object.
 */
export const openYamlFileAsObject = async <T>(filePath: string): Promise<T> => {
  try {
    const yamlFileBuffer = await fs.readFile(filePath, 'utf8');
 
    return YAML.load(yamlFileBuffer) as T;
  } catch (error: any) {
    throw new ReadFileError(error.message);
  }
};
 
/**
 * Saves given `yaml` dump as a file.
 */
export const saveYamlFileAs = async (object: any, pathToFile: string) => {
  try {
    const dirPath = path.dirname(pathToFile);
    await fs.mkdir(dirPath, {recursive: true});
    const yamlString = YAML.dump(object, {noRefs: true});
 
    return await fs.writeFile(pathToFile, yamlString);
  } catch (error: any) {
    throw new WriteFileError(error.message);
  }
};
 
/**
 * Checks if given `fileName` is yaml.
 */
export const checkIfFileIsYaml = (fileName: string) => {
  const yamlFileTypes = ['yaml', 'yml'];
  const splittedParts = fileName.split('.');
  const lastIndex = splittedParts.length - 1;
  const extension = splittedParts[lastIndex];
 
  return yamlFileTypes.includes(extension);
};