2020-03-30 23:23:02 +03:00
|
|
|
const Promise = require('bluebird');
|
2020-05-26 21:10:29 +03:00
|
|
|
const errors = require('@tryghost/errors');
|
2021-06-15 17:36:27 +03:00
|
|
|
const logging = require('@tryghost/logging');
|
2017-04-04 19:07:35 +03:00
|
|
|
|
2021-10-04 18:50:07 +03:00
|
|
|
const {hbs} = require('../rendering');
|
|
|
|
|
2017-04-04 19:07:35 +03:00
|
|
|
// Register an async handlebars helper for a given handlebars instance
|
2020-10-20 02:02:56 +03:00
|
|
|
function asyncHelperWrapper(hbsInstance, name, fn) {
|
|
|
|
hbsInstance.registerAsyncHelper(name, function returnAsync(context, options, cb) {
|
2017-04-04 19:07:35 +03:00
|
|
|
// Handle the case where we only get context and cb
|
|
|
|
if (!cb) {
|
|
|
|
cb = options;
|
|
|
|
options = undefined;
|
|
|
|
}
|
|
|
|
|
2021-10-04 18:50:07 +03:00
|
|
|
// Wrap the function passed in with a Promise.resolve so it can return either a promise or a value
|
2017-08-27 18:06:44 +03:00
|
|
|
Promise.resolve(fn.call(this, context, options)).then(function asyncHelperSuccess(result) {
|
2017-04-04 19:07:35 +03:00
|
|
|
cb(result);
|
2017-08-27 18:06:44 +03:00
|
|
|
}).catch(function asyncHelperError(err) {
|
2021-12-01 13:22:01 +03:00
|
|
|
const wrappedErr = errors.utils.isGhostError(err) ? err : new errors.IncorrectUsageError({
|
2020-04-29 18:44:27 +03:00
|
|
|
err: err,
|
|
|
|
context: 'registerAsyncThemeHelper: ' + name,
|
|
|
|
errorDetails: {
|
|
|
|
originalError: err
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2021-10-04 18:50:07 +03:00
|
|
|
const result = process.env.NODE_ENV === 'development' ? wrappedErr : '';
|
2017-08-27 18:06:44 +03:00
|
|
|
|
2020-03-30 23:23:02 +03:00
|
|
|
logging.error(wrappedErr);
|
2017-08-27 18:06:44 +03:00
|
|
|
|
2020-10-20 02:02:56 +03:00
|
|
|
cb(new hbsInstance.SafeString(result));
|
2017-04-04 19:07:35 +03:00
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// Register a handlebars helper for themes
|
|
|
|
module.exports.registerThemeHelper = function registerThemeHelper(name, fn) {
|
|
|
|
hbs.registerHelper(name, fn);
|
|
|
|
};
|
|
|
|
|
|
|
|
// Register an async handlebars helper for themes
|
|
|
|
module.exports.registerAsyncThemeHelper = function registerAsyncThemeHelper(name, fn) {
|
|
|
|
asyncHelperWrapper(hbs, name, fn);
|
|
|
|
};
|