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

USF-1877: Headers from config #267

Merged
merged 16 commits into from
Jan 15, 2025
Merged
12 changes: 6 additions & 6 deletions blocks/header/searchbar.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ import { getConfigValue } from '../../scripts/configs.js';
await loadScript(widgetProd);

const storeDetails = {
environmentId: await getConfigValue('commerce-environment-id'),
environmentId: await getConfigValue('commerce.headers.cs.Magento-Environment-Id'),
environmentType: (await getConfigValue('commerce-endpoint')).includes('sandbox') ? 'testing' : '',
apiKey: await getConfigValue('commerce-x-api-key'),
apiKey: await getConfigValue('commerce.headers.cs.x-api-key'),
apiUrl: await getConfigValue('commerce-endpoint'),
websiteCode: await getConfigValue('commerce-website-code'),
storeCode: await getConfigValue('commerce-store-code'),
storeViewCode: await getConfigValue('commerce-store-view-code'),
websiteCode: await getConfigValue('commerce.headers.cs.Magento-Website-Code'),
storeCode: await getConfigValue('commerce.headers.cs.Magento-Store-Code'),
storeViewCode: await getConfigValue('commerce.headers.cs.Magento-Store-View-Code'),
config: {
pageSize: 8,
perPageConfig: {
Expand All @@ -26,7 +26,7 @@ import { getConfigValue } from '../../scripts/configs.js';
allowAllProducts: false,
},
context: {
customerGroup: await getConfigValue('commerce-customer-group'),
customerGroup: await getConfigValue('commerce.headers.cs.Magento-Customer-Group'),
},
route: ({ sku, urlKey }) => `/products/${urlKey}/${sku}`,
searchRoute: {
Expand Down
12 changes: 6 additions & 6 deletions blocks/product-list-page/product-list-page.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ export default async function decorate(block) {
block.textContent = '';

const storeDetails = {
environmentId: await getConfigValue('commerce-environment-id'),
environmentId: await getConfigValue('commerce.headers.cs.Magento-Environment-Id'),
environmentType: (await getConfigValue('commerce-endpoint')).includes('sandbox') ? 'testing' : '',
apiKey: await getConfigValue('commerce-x-api-key'),
apiKey: await getConfigValue('commerce.headers.cs.x-api-key'),
apiUrl: await getConfigValue('commerce-endpoint'),
websiteCode: await getConfigValue('commerce-website-code'),
storeCode: await getConfigValue('commerce-store-code'),
storeViewCode: await getConfigValue('commerce-store-view-code'),
websiteCode: await getConfigValue('commerce.headers.cs.Magento-Website-Code'),
storeCode: await getConfigValue('commerce.headers.cs.Magento-Store-Code'),
storeViewCode: await getConfigValue('commerce.headers.cs.Magento-Store-View-Code'),
config: {
pageSize: 8,
perPageConfig: {
Expand All @@ -42,7 +42,7 @@ export default async function decorate(block) {
},
},
context: {
customerGroup: await getConfigValue('commerce-customer-group'),
customerGroup: await getConfigValue('commerce.headers.cs.Magento-Customer-Group'),
},
route: ({ sku, urlKey }) => {
const a = new URL(window.location.origin);
Expand Down
2 changes: 1 addition & 1 deletion blocks/product-recommendations/product-recommendations.js
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ async function loadRecommendation(block, context, visibility, filters) {
return;
}

const storeViewCode = await getConfigValue('commerce-store-view-code');
const storeViewCode = await getConfigValue('commerce.headers.cs.Magento-Store-View-Code');

if (unitsPromise) {
return;
Expand Down
18 changes: 8 additions & 10 deletions scripts/commerce.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
/* eslint-disable import/prefer-default-export, import/no-cycle */
import { getConfigValue, getCookie } from './configs.js';
import {
getConfigValue, getCookie, getHeaders,
} from './configs.js';
import { getConsent } from './scripts.js';

/* Common query fragments */
Expand All @@ -20,22 +22,18 @@ export const priceFieldsFragment = `fragment priceFields on ProductViewPrice {
}`;

export async function commerceEndpointWithQueryParams() {
// Set Query Parameters so they can be appended to the endpoint
const urlWithQueryParams = new URL(await getConfigValue('commerce-endpoint'));
urlWithQueryParams.searchParams.append('Magento-Environment-Id', await getConfigValue('commerce-environment-id'));
urlWithQueryParams.searchParams.append('Magento-Website-Code', await getConfigValue('commerce-website-code'));
urlWithQueryParams.searchParams.append('Magento-Store-View-Code', await getConfigValue('commerce-store-view-code'));
urlWithQueryParams.searchParams.append('Magento-Store-Code', await getConfigValue('commerce-store-code'));
urlWithQueryParams.searchParams.append('Magento-Customer-Group', await getConfigValue('commerce-customer-group'));
// Set some query parameters for use as a cache-buster. No other purpose.
urlWithQueryParams.searchParams.append('ac-storecode', await getConfigValue('commerce.headers.cs.Magento-Store-Code'));
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

major change - we are reverting back to rely on headers for request data differentation. the only query param we add is now done for cache busting purposes.

return urlWithQueryParams;
}

/* Common functionality */

export async function performCatalogServiceQuery(query, variables) {
const headers = {
...(await getHeaders('cs')),
'Content-Type': 'application/json',
'x-api-key': await getConfigValue('commerce-x-api-key'),
};

const apiCall = await commerceEndpointWithQueryParams();
Expand Down Expand Up @@ -66,7 +64,7 @@ export async function performMonolithGraphQLQuery(query, variables, GET = true,

const headers = {
'Content-Type': 'application/json',
Store: await getConfigValue('commerce-store-view-code'),
Store: await getConfigValue('commerce.headers.cs.Magento-Store-View-Code'),
};

if (USE_TOKEN) {
Expand Down Expand Up @@ -161,7 +159,7 @@ export async function trackHistory() {
return;
}
// Store product view history in session storage
const storeViewCode = await getConfigValue('commerce-store-view-code');
const storeViewCode = await getConfigValue('commerce.headers.cs.Magento-Store-View-Code');
window.adobeDataLayer.push((dl) => {
dl.addEventListener('adobeDataLayer:change', (event) => {
if (!event.productContext) {
Expand Down
18 changes: 18 additions & 0 deletions scripts/configs.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,24 @@ export const getConfigValue = async (configParam, environment) => {
return configElements.find((c) => c.key === configParam)?.value;
};

/**
* Retrieves headers from config entries like commerce.headers.pdp.my-header, etc and
* returns as object of all headers like { my-header: value, ... }
*/
export const getHeaders = async (scope, environment) => {
const env = environment || calcEnvironment();
const config = await getConfigForEnvironment(env);
const configElements = config.data.filter((el) => el?.key.includes(`headers.${scope}`));

return configElements.reduce((obj, item) => {
let { key } = item;
if (key.includes(`commerce.headers.${scope}.`)) {
key = key.replace(`commerce.headers.${scope}.`, '');
}
return { ...obj, [key]: item.value };
}, {});
};

export const getCookie = (cookieName) => {
const cookies = document.cookie.split(';');
let foundValue;
Expand Down
8 changes: 4 additions & 4 deletions scripts/delayed.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ async function initAnalytics() {
// Load Commerce events SDK and collector
if (getConsent('commerce-collection')) {
const config = {
environmentId: await getConfigValue('commerce-environment-id'),
environmentId: await getConfigValue('commerce.headers.cs.Magento-Environment-Id'),
environment: await getConfigValue('commerce-environment'),
storeUrl: await getConfigValue('commerce-store-url'),
websiteId: parseInt(await getConfigValue('commerce-website-id'), 10),
websiteCode: await getConfigValue('commerce-website-code'),
websiteCode: await getConfigValue('commerce.headers.cs.Magento-Website-Code'),
storeId: parseInt(await getConfigValue('commerce-store-id'), 10),
storeCode: await getConfigValue('commerce-store-code'),
storeCode: await getConfigValue('commerce.headers.cs.Magento-Store-Code'),
storeViewId: parseInt(await getConfigValue('commerce-store-view-id'), 10),
storeViewCode: await getConfigValue('commerce-store-view-code'),
storeViewCode: await getConfigValue('commerce.headers.cs.Magento-Store-View-Code'),
websiteName: await getConfigValue('commerce-website-name'),
storeName: await getConfigValue('commerce-store-name'),
storeViewName: await getConfigValue('commerce-store-view-name'),
Expand Down
6 changes: 4 additions & 2 deletions scripts/initializers/account.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { initializers } from '@dropins/tools/initializer.js';
import { initialize } from '@dropins/storefront-account/api.js';
import { initialize, setFetchGraphQlHeaders } from '@dropins/storefront-account/api.js';
import { initializeDropin } from './index.js';
import { fetchPlaceholders } from '../aem.js';
import { getHeaders } from '../configs.js';

await initializeDropin(async () => {
const labels = await fetchPlaceholders();
setFetchGraphQlHeaders(await getHeaders('account'));

const labels = await fetchPlaceholders();
const langDefinitions = {
default: {
...labels,
Expand Down
6 changes: 4 additions & 2 deletions scripts/initializers/auth.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
/* eslint-disable import/no-cycle */
import { initializers } from '@dropins/tools/initializer.js';
import { initialize } from '@dropins/storefront-auth/api.js';
import { initialize, setFetchGraphQlHeaders } from '@dropins/storefront-auth/api.js';
import { initializeDropin } from './index.js';
import { fetchPlaceholders } from '../aem.js';
import { getHeaders } from '../configs.js';

await initializeDropin(async () => {
const labels = await fetchPlaceholders();
setFetchGraphQlHeaders(await getHeaders('auth'));

const labels = await fetchPlaceholders();
const langDefinitions = {
default: {
...labels,
Expand Down
6 changes: 4 additions & 2 deletions scripts/initializers/cart.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
/* eslint-disable import/no-cycle */
import { initializers } from '@dropins/tools/initializer.js';
import { initialize } from '@dropins/storefront-cart/api.js';
import { initialize, setFetchGraphQlHeaders } from '@dropins/storefront-cart/api.js';
import { initializeDropin } from './index.js';
import { fetchPlaceholders } from '../aem.js';
import { getHeaders } from '../configs.js';

await initializeDropin(async () => {
const labels = await fetchPlaceholders();
setFetchGraphQlHeaders(await getHeaders('cart'));

const labels = await fetchPlaceholders();
const langDefinitions = {
default: {
...labels,
Expand Down
6 changes: 4 additions & 2 deletions scripts/initializers/checkout.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { initializers } from '@dropins/tools/initializer.js';
import { initialize } from '@dropins/storefront-checkout/api.js';
import { initialize, setFetchGraphQlHeaders } from '@dropins/storefront-checkout/api.js';
import { initializeDropin } from './index.js';
import { fetchPlaceholders } from '../aem.js';
import { getHeaders } from '../configs.js';

await initializeDropin(async () => {
const labels = await fetchPlaceholders();
setFetchGraphQlHeaders(await getHeaders('checkout'));

const labels = await fetchPlaceholders();
const langDefinitions = {
default: {
...labels,
Expand Down
14 changes: 8 additions & 6 deletions scripts/initializers/order.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { events } from '@dropins/tools/event-bus.js';
import { initializers } from '@dropins/tools/initializer.js';
import { initialize } from '@dropins/storefront-order/api.js';
import { checkIsAuthenticated } from '../configs.js';
import { initialize, setFetchGraphQlHeaders } from '@dropins/storefront-order/api.js';
import { checkIsAuthenticated, getHeaders } from '../configs.js';
import { initializeDropin } from './index.js';
import { fetchPlaceholders } from '../aem.js';

Expand All @@ -19,22 +19,24 @@ import {

await initializeDropin(async () => {
const { pathname, searchParams } = new URL(window.location.href);
if (pathname.includes(CUSTOMER_ORDERS_PATH)) {
return;
}
sirugh marked this conversation as resolved.
Show resolved Hide resolved
const isAccountPage = pathname.includes(CUSTOMER_PATH);
const orderRef = searchParams.get('orderRef');
const returnRef = searchParams.get('returnRef');
const orderNumber = searchParams.get('orderNumber');
const isTokenProvided = orderRef && orderRef.length > 20;

setFetchGraphQlHeaders(await getHeaders('order'));

const labels = await fetchPlaceholders();
const langDefinitions = {
default: {
...labels,
},
};

if (pathname.includes(CUSTOMER_ORDERS_PATH)) {
return;
}

const pathsRequiringRedirects = [
ORDER_DETAILS_PATH,
CUSTOMER_ORDER_DETAILS_PATH,
Expand Down
4 changes: 2 additions & 2 deletions scripts/initializers/pdp.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
getSkuFromUrl,
loadErrorPage,
} from '../commerce.js';
import { getConfigValue } from '../configs.js';
import { getHeaders } from '../configs.js';
import { fetchPlaceholders } from '../aem.js';

export const IMAGES_SIZES = {
Expand All @@ -30,8 +30,8 @@ await initializeDropin(async () => {

// Set Fetch Headers (Service)
setFetchGraphQlHeaders({
...(await getHeaders('cs')),
'Content-Type': 'application/json',
'x-api-key': await getConfigValue('commerce-x-api-key'),
});

const sku = getSkuFromUrl();
Expand Down
9 changes: 7 additions & 2 deletions tools/pdp-metadata/pdp-metadata.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@ const configFile = `${basePath}/configs.json?sheet=prod`;
async function performCatalogServiceQuery(config, query, variables) {
const headers = {
'Content-Type': 'application/json',
'x-api-key': config['commerce-x-api-key'],
'x-api-key': config['commerce.headers.cs.x-api-key'],
'Magento-Customer-Group': config['commerce.headers.cs.Magento-Customer-Group'],
'Magento-Environment-Id': config['commerce.headers.cs.Magento-Environment-Id'],
'Magento-Store-Code': config['commerce.headers.cs.Magento-Store-Code'],
'Magento-Store-View-Code': config['commerce.headers.cs.Magento-Store-View-Code'],
'Magento-Website-Code': config['commerce.headers.cs.Magento-Website-Code'],
};

const apiCall = await commerceEndpointWithQueryParams();
Expand Down Expand Up @@ -166,7 +171,7 @@ async function addVariantsToProducts(products, config) {
item_${i}: variants(sku: "${product.productView.sku}") {
...ProductVariant
}
`
`
}).join('\n')}
}${variantsFragment}`;

Expand Down
18 changes: 9 additions & 9 deletions tools/picker/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const defaultConfig = 'prod';

/**
* List of blocks to be available in the picker.
*
*
* Format: Object with key -> block mapping. Each block is defined by the following properties:
* key: Unique key, must be same as the key in the object
* name: Displayed name of the block
Expand Down Expand Up @@ -116,17 +116,17 @@ const blocks = {

async function performCatalogServiceQuery(query, config, variables) {
const headers = {
'x-api-key': config['commerce-x-api-key'],
'Content-Type': 'application/json',
'x-api-key': config['commerce.headers.cs.x-api-key'],
'Magento-Customer-Group': config['commerce.headers.cs.Magento-Customer-Group'],
'Magento-Environment-Id': config['commerce.headers.cs.Magento-Environment-Id'],
'Magento-Store-Code': config['commerce.headers.cs.Magento-Store-Code'],
'Magento-Store-View-Code': config['commerce.headers.cs.Magento-Store-View-Code'],
'Magento-Website-Code': config['commerce.headers.cs.Magento-Website-Code'],
};

// Set Query Parameters so they can be appended to the endpoint
// set query params if provided, or fall back to header value
sirugh marked this conversation as resolved.
Show resolved Hide resolved
const apiCall = new URL(config['commerce-endpoint']);
apiCall.searchParams.append("Magento-Environment-Id", config['commerce-environment-id']);
apiCall.searchParams.append("Magento-Website-Code", config['commerce-website-code']);
apiCall.searchParams.append("Magento-Store-View-Code", config['commerce-store-view-code']);
apiCall.searchParams.append("Magento-Store-Code", config['commerce-store-code']);
apiCall.searchParams.append("Magento-Customer-Group", config['commerce-customer-group']);
apiCall.searchParams.append('query', query.replace(/(?:\r\n|\r|\n|\t|[\s]{4})/g, ' ')
.replace(/\s\s+/g, ' '));
apiCall.searchParams.append('variables', variables ? JSON.stringify(variables) : null);
Expand Down Expand Up @@ -196,4 +196,4 @@ if (app) {
getItems={getItems}
configFiles={configFiles}
defaultConfig={defaultConfig} />, app);
}
}
Loading