UNPKG

@scayle/storefront-nuxt

Version:

Nuxt integration for the SCAYLE Commerce Engine and Storefront API

73 lines (72 loc) 2.78 kB
import { getRequestHeaders, getRequestHost, getRequestURL } from "h3"; import { joinURL } from "ufo"; export function getBootstrapPath(url, baseUrl) { const queryUrl = url.searchParams.get("url"); const path = url.pathname === joinURL(baseUrl, "/__nuxt_error") && queryUrl ? joinURL(baseUrl, queryUrl) : url.pathname; return { path, originalPath: url.pathname }; } const getShopByDomain = (event, shops) => { const host = getRequestHost(event, { xForwardedHost: true }); return shops.find((s) => s.domain === host); }; export const getShopByPath = (event, shops, appBasePath) => { const url = getRequestURL(event); const { path } = getBootstrapPath(url, appBasePath); const localeIndex = appBasePath !== "/" ? 2 : 1; const prefix = path.split("/")?.[localeIndex]; const matchesShopPrefix = (shop) => Array.isArray(shop.path) ? shop.path.includes(prefix) : shop.path === prefix; return shops.find(matchesShopPrefix); }; const getShopByPathOrDefault = (event, shops, appBasePath) => { const defaultShop = shops.find((shop) => shop.isDefault); const otherShops = shops.filter((shop) => !shop.isDefault); return getShopByPath(event, otherShops, appBasePath) ?? defaultShop; }; export const convertShopsToList = (shops) => { if (Array.isArray(shops)) { return shops; } return Object.values(shops); }; export function getApiBasePath(storefrontConfig, baseUrl) { const apiPath = storefrontConfig.apiBasePath || "/api"; return joinURL(baseUrl, apiPath); } export function getCurrentShopConfigForRequest(event, storefrontConfig, runtimeConfig) { let $shopConfig; const { shopSelector, shops } = storefrontConfig; const shopsList = convertShopsToList(shops); const headers = getRequestHeaders(event); const shopId = headers["x-shop-id"]; if (shopId) { $shopConfig = shopsList.find((s) => s.shopId === Number(shopId)); } else if (shopSelector === "domain") { $shopConfig = getShopByDomain(event, shopsList); } else if (shopSelector === "path") { $shopConfig = getShopByPath(event, shopsList, runtimeConfig.baseURL); } else if (shopSelector === "path_or_default") { $shopConfig = getShopByPathOrDefault( event, shopsList, runtimeConfig.baseURL ); } return $shopConfig; } export function getPublicShopData(data, currentShopId, apiBasePath, publicShopData = []) { const additionalShopData = {}; publicShopData.forEach((key) => additionalShopData[key] = data[key]); return { domain: data.domain, path: Array.isArray(data.path) ? data.path[0] : data.path, locale: data.locale, shopId: data.shopId, currency: data.currency, isActive: data.shopId === currentShopId, checkout: { host: data.checkout.host }, apiBasePath, ...additionalShopData }; }