Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Jambo build validation hook #229

Merged
merged 8 commits into from
Jun 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/commands/build/pagewriter.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const UserError = require('../../errors/usererror');
const { NO_LOCALE } = require('../../constants');
const LocalizationConfig = require('../../models/localizationconfig');
const TemplateArgsBuilder = require('./templateargsbuilder');
const TemplateDataValidator = require('./templatedatavalidator');
const { info } = require('../../utils/logger');

/**
Expand All @@ -30,12 +31,20 @@ module.exports = class PageWriter {
*/
this._templateArgsBuilder =
new TemplateArgsBuilder(config.templateDataFormatterHook);

/**
* @type {TemplateDataValidator}
*/
this._templateDataValidator =
new TemplateDataValidator(config.templateDataValidationHook);
}

/**
* Writes a file to the output directory per page in the given PageSet.
*
* @param {PageSet} pageSet the collection of pages to generate
* @throws {UserError} on missing page config(s), validation hook execution
* failure, and invalid template data using Theme's validation hook
*/
writePages(pageSet) {
if (!pageSet || pageSet.getPages().length < 1) {
Expand All @@ -51,7 +60,6 @@ module.exports = class PageWriter {
throw new UserError(`Error: No config found for page: ${page.getName()}`);
}

info(`Writing output file for the '${page.getName()}' page`);
const templateArguments = this._templateArgsBuilder.buildArgs({
relativePath: this._calculateRelativePath(page.getOutputPath()),
pageName: page.getName(),
Expand All @@ -61,7 +69,15 @@ module.exports = class PageWriter {
locale: pageSet.getLocale(),
env: this._env
});

if(!this._templateDataValidator.validate({
pageName: page.getName(),
pageData: templateArguments
})) {
throw new UserError('Invalid page template configuration(s).');
}

info(`Writing output file for the '${page.getName()}' page`);
const template = hbs.compile(page.getTemplateContents());
const outputHTML = template(templateArguments);

Expand Down
3 changes: 3 additions & 0 deletions src/commands/build/sitesgenerator.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,10 +178,13 @@ class SitesGenerator {

const templateDataFormatterHook = path.resolve(
config.dirs.themes, config.defaultTheme, 'hooks', 'templatedataformatter.js');
const templateDataValidationHook = path.resolve(
config.dirs.themes, config.defaultTheme, 'hooks', 'templatedatavalidator.js');
// Write pages
new PageWriter({
outputDirectory: config.dirs.output,
templateDataFormatterHook: templateDataFormatterHook,
templateDataValidationHook: templateDataValidationHook,
env: env,
}).writePages(pageSet);
}
Expand Down
48 changes: 48 additions & 0 deletions src/commands/build/templatedatavalidator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
const fs = require('file-system');
const UserError = require('../../errors/usererror');
const { isCustomError } = require('../../utils/errorutils');
const { info } = require('../../utils/logger');

/**
* TemplateDataValidator is reponsible for checking data supplied to a page
* using Theme's custom validation steps (if any).
*/
module.exports = class TemplateDataValidator {
constructor(templateDataValidationHook) {
/**
* The path to template data validation hook.
* @type {string}
*/
this._templateDataValidationHook = templateDataValidationHook;

/**
* Whether or not the file for template data validation hook exists
* @type {boolean}
*/
this._hasHook = fs.existsSync(this._templateDataValidationHook);
}

/**
* Execute validation hook's function if file exists
*
* @param {Object} page
* @param {string} page.pageName name of the current page
* @param {Object} page.pageData template arguments for the current page
* @throws {UserError} on failure to execute hook
* @returns {boolean} whether or not to throw an exception on bad template arguments
*/
validate({ pageName, pageData }) {
if (!this._hasHook) {
return true;
}
try {
info(`Validating configuration for page "${pageName}".`);
const validatorFunction = require(this._templateDataValidationHook);
return validatorFunction(pageData);
} catch (err) {
const msg =
`Error executing validation hook from ${this._templateDataValidationHook}: `;
throw new UserError(msg, err.stack);
}
}
}
107 changes: 107 additions & 0 deletions tests/commands/build/templatedatavalidator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
const TemplateDataValidator = require('../../../src/commands/build/templatedatavalidator');
const path = require('path');
const UserError = require('../../../src/errors/usererror');

describe('TemplateDataValidator validates config data using hook properly', () => {
const currentPageConfig = {
url: 'examplePage.html',
verticalKey: 'examplePage',
pageTitle: 'Example Page',
pageSettings: { search: { verticalKey: 'examplePage', defaultInitialSearch: '' } },
componentSettings: {
prop: 'example1',
},
verticalsToConfig: {
examplePage: {
prop: 'example2'
}
}
};
const verticalConfigs = {
page1: {
config: {
prop: 'example'
}
},
page2: {
config: {
prop: 'example2'
}
}
};
const global_config = {
sdkVersion: 'X.X',
apiKey: 'exampleKey',
experienceKey: 'slanswers',
locale: 'en'
};
const params = {
example: 'param'
};
const relativePath = '..';
const env = {
envVar: 'envVar',
};

it('does not throw an error with a correct config', () => {
const templateDataValidationHook = path.resolve(
__dirname, '../../fixtures/hooks/templatedatavalidator.js');
const templateData = {
currentPageConfig,
verticalConfigs : verticalConfigs,
global_config : global_config,
params : params,
relativePath: relativePath,
env: env
};

const isValid = new TemplateDataValidator(templateDataValidationHook).validate({
pageName: 'examplePage',
pageData: templateData
});
expect(isValid).toEqual(true);
});

it('throws an error when a field in config is missing', () => {
const templateDataValidationHook = path.resolve(
__dirname, '../../fixtures/hooks/templatedatavalidator.js');
const global_config_missing_key = {};
const templateData = {
currentPageConfig,
verticalConfigs : verticalConfigs,
global_config : global_config_missing_key,
params : params,
relativePath: relativePath,
env: env
};

const isValid = new TemplateDataValidator(templateDataValidationHook).validate({
pageName: 'examplePage',
pageData: templateData
});
expect(isValid).toEqual(false);

});


it('does not throw error, gracefully ignore missing config field in bad pages', () => {
const templateDataValidationHook = path.resolve(
__dirname, '../../fixtures/hooks/templatedatavalidator.js');
const params_missing_field = {};
const templateData = {
currentPageConfig,
verticalConfigs : verticalConfigs,
global_config : global_config,
params : params_missing_field,
relativePath: relativePath,
env: env
};

const isValid = new TemplateDataValidator(templateDataValidationHook).validate({
pageName: 'examplePage',
pageData: templateData
});
expect(isValid).toEqual(true);
});

});
18 changes: 18 additions & 0 deletions tests/fixtures/hooks/templatedatavalidator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const { warn } = require('../../../src/utils/logger');
/**
* A test data validator hook.
*
* @param {Object} pageData configuration(s) of a page template
* @returns {boolean} false if validator should throw an error
*/
module.exports = function (pageData) {
if(!pageData["params"]["example"]) {
warn('Missing Info: param example in config file(s)');
return true; //gracefully ignore missing param on page
}
if(!pageData["global_config"]["experienceKey"]) {
warn('Missing Info: experienceKey in config file(s)');
return false;
}
return true;
}