All files / src/context/yaml/handlers hooks.ts

96.42% Statements 27/28
75% Branches 6/8
100% Functions 4/4
96.29% Lines 26/27

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 62 63 64 65 661x 1x 1x   1x 1x                 41x 41x   2x     1x   1x     1x   1x             6x   6x         6x 6x   6x     3x 3x 3x 3x 3x   3x     6x     1x         1x  
import path from 'path';
import fs from 'fs-extra';
import { constants } from '../../../tools';
 
import { sanitize } from '../../../utils';
import log from '../../../logger';
 
import { YAMLHandler } from '.';
import YAMLContext from '..';
import { Asset, ParsedAsset } from '../../../types';
 
type ParsedHooks = ParsedAsset<'hooks', Asset[]>;
 
async function parse(context: YAMLContext): Promise<ParsedHooks> {
  const { hooks } = context.assets;
  if (!hooks) return { hooks: null };
 
  return {
    hooks: [
      ...hooks.map((hook) => {
        Eif (hook.script) {
          //@ts-ignore TODO: understand why two arguments are passed when context.loadFile only accepts one
          hook.script = context.loadFile(hook.script, constants.HOOKS_DIRECTORY);
        }
 
        hook.name = hook.name.toLowerCase().replace(/\s/g, '-');
 
        return { ...hook };
      }),
    ],
  };
}
 
async function dump(context: YAMLContext): Promise<ParsedHooks> {
  let hooks = context.assets.hooks;
 
  Iif (!hooks) {
    return { hooks: null };
  }
 
  // Create hooks folder
  const hooksFolder = path.join(context.basePath, 'hooks');
  fs.ensureDirSync(hooksFolder);
 
  hooks = hooks.map((hook) => {
    // Dump hook code to file
    // For cases when hook does not have `meta['hook-name']`
    hook.name = hook.name || hook.id;
    const codeName = sanitize(`${hook.name}.js`);
    const codeFile = path.join(hooksFolder, codeName);
    log.info(`Writing ${codeFile}`);
    fs.writeFileSync(codeFile, hook.script);
 
    return { ...hook, script: `./hooks/${codeName}` };
  });
 
  return { hooks };
}
 
const hooksHandler: YAMLHandler<ParsedHooks> = {
  parse,
  dump,
};
 
export default hooksHandler;