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