0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-02-17 23:44:39 -05:00
ghost/core/frontend/services/helpers/handlebars.js
Hannah Wolfe 412d290a30
Refactored async helpers to use async/await (#14781)
- async/await makes the code easier to read
- also means we can get rid of usages of Promise, and some unnecessary usages of Bluebird
- this refactor is done for the 4 async helpers and the code that wraps async helpers so the whole pipeline is async/await and more understandable
2022-05-11 09:51:38 +01:00

44 lines
1.4 KiB
JavaScript

const errors = require('@tryghost/errors');
const logging = require('@tryghost/logging');
const {hbs} = require('../handlebars');
// Register an async handlebars helper for a given handlebars instance
function asyncHelperWrapper(hbsInstance, name, fn) {
hbsInstance.registerAsyncHelper(name, async function returnAsync(context, options, cb) {
// Handle the case where we only get context and cb
if (!cb) {
cb = options;
options = undefined;
}
try {
const response = await fn.call(this, context, options);
cb(response);
} catch (error) {
const wrappedErr = errors.utils.isGhostError(error) ? error : new errors.IncorrectUsageError({
err: error,
context: 'registerAsyncThemeHelper: ' + name,
errorDetails: {
originalError: error
}
});
const response = process.env.NODE_ENV === 'development' ? wrappedErr : '';
logging.error(wrappedErr);
cb(new hbsInstance.SafeString(response));
}
});
}
// 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);
};