From 49f48c0f09ba2b07c0af9725ca24941fa2144ce3 Mon Sep 17 00:00:00 2001 From: Fabien O'Carroll Date: Wed, 21 Jul 2021 11:28:13 +0100 Subject: [PATCH] Made a single request for products in theme middleware refs https://github.com/TryGhost/Team/issues/907 The logic to populate the `@price` data and the `@products` data both rely on the same product data, but were each making their own request to the API. This refactor removes the request from the legacy `@price` data, which should cut the database queries in half. --- .../services/theme-engine/middleware.js | 39 ++++++------------- 1 file changed, 11 insertions(+), 28 deletions(-) diff --git a/core/frontend/services/theme-engine/middleware.js b/core/frontend/services/theme-engine/middleware.js index 0adcacb06c..65e9360fb8 100644 --- a/core/frontend/services/theme-engine/middleware.js +++ b/core/frontend/services/theme-engine/middleware.js @@ -36,12 +36,7 @@ function ensureActiveTheme(req, res, next) { next(); } -/* - * @TODO - * This should be definitely refactored and we need to consider _some_ - * members settings as publicly readable - */ -async function haxGetMembersPriceData() { +function calculateLegacyPriceData(products) { const defaultPrice = { amount: 0, currency: 'usd', @@ -63,31 +58,19 @@ async function haxGetMembersPriceData() { }; } - try { - const {products} = await api.canary.products.browse({ - include: ['monthly_price','yearly_price'] - }); + const defaultProduct = products[0] || {}; - const defaultProduct = products[0]; + const monthlyPrice = makePriceObject(defaultProduct.monthly_price || defaultPrice); - const monthlyPrice = makePriceObject(defaultProduct.monthly_price || defaultPrice); + const yearlyPrice = makePriceObject(defaultProduct.yearly_price || defaultPrice); - const yearlyPrice = makePriceObject(defaultProduct.yearly_price || defaultPrice); + const priceData = { + monthly: monthlyPrice, + yearly: yearlyPrice, + currency: monthlyPrice ? monthlyPrice.currency : defaultPrice.currency + }; - const priceData = { - monthly: monthlyPrice, - yearly: yearlyPrice, - currency: monthlyPrice ? monthlyPrice.currency : defaultPrice.currency - }; - - return priceData; - } catch (err) { - return { - monthly: makePriceObject(defaultPrice), - yearly: makePriceObject(defaultPrice), - currency: 'usd' - }; - } + return priceData; } async function getProductAndPricesData() { @@ -131,8 +114,8 @@ async function updateGlobalTemplateOptions(req, res, next) { posts_per_page: activeTheme.get().config('posts_per_page'), image_sizes: activeTheme.get().config('image_sizes') }; - const priceData = await haxGetMembersPriceData(); const productData = await getProductAndPricesData(); + const priceData = calculateLegacyPriceData(productData); let products = null; let product = null;