All files / src/context/directory/handlers roles.ts

96.15% Statements 25/26
87.5% Branches 7/8
100% Functions 4/4
95.83% Lines 23/24

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 621x 1x 1x   1x 1x               54x 54x   2x   2x 4x           4x     2x           2x     2x   1x 1x   1x 2x 2x     2x       2x       1x         1x  
import fs from 'fs-extra';
import path from 'path';
import { constants } from '../../../tools';
 
import log from '../../../logger';
import { getFiles, existsMustBeDir, dumpJSON, loadJSON, sanitize } from '../../../utils';
import { DirectoryHandler } from '.';
import DirectoryContext from '..';
import { Asset, ParsedAsset } from '../../../types';
 
type ParsedRoles = ParsedAsset<'roles', Asset[]>;
 
function parse(context: DirectoryContext): ParsedRoles {
  const rolesFolder = path.join(context.filePath, constants.ROLES_DIRECTORY);
  if (!existsMustBeDir(rolesFolder)) return { roles: null }; // Skip
 
  const files = getFiles(rolesFolder, ['.json']);
 
  const roles = files.map((f) => {
    const role = {
      ...loadJSON(f, {
        mappings: context.mappings,
        disableKeywordReplacement: context.disableKeywordReplacement,
      }),
    };
    return role;
  });
 
  return {
    roles,
  };
}
 
async function dump(context: DirectoryContext) {
  const { roles } = context.assets;
 
  // API returns an empty object if no grants are present
  if (!roles || roles.constructor === Object) return; // Skip, nothing to dump
 
  const rolesFolder = path.join(context.filePath, constants.ROLES_DIRECTORY);
  fs.ensureDirSync(rolesFolder);
 
  roles.forEach((role) => {
    const roleFile = path.join(rolesFolder, sanitize(`${role.name}.json`));
    log.info(`Writing ${roleFile}`);
 
    // remove empty description
    Iif (role.description === null) {
      delete role.description;
    }
 
    dumpJSON(roleFile, role);
  });
}
 
const rolesHandler: DirectoryHandler<ParsedRoles> = {
  parse,
  dump,
};
 
export default rolesHandler;