Inicialización de la aplicación
Application Load · Nuxt
Application Load es la primera solicitud que tu tienda hace a su backend personal. Devuelve los ajustes y el contenido inicial necesarios para mostrar la interfaz, el perfil del cliente actual cuando ha iniciado sesión y los métodos de la API disponibles en esta sesión.
/api/apploadQué contiene la respuesta
page_data — los datos de la aplicación dentro de la respuesta de la API. Sus cuatro secciones principales tienen funciones distintas:
Datos iniciales de la tienda, perfil del cliente y endpoints de la API disponibles.
app/interfaces/basklee/appBase/IAppLoad.tsimport type { IAppLoadCommon } from '@/interfaces/basklee/appBase/IAppLoadCommon';
import type { IApploadUserProfile } from '@/interfaces/basklee/appBase/IApploadUserProfile';
import type { IAppLoadPathsRecord } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonPath';
export interface IAppLoad {
// Ajustes compartidos de la tienda y datos iniciales.
init: IAppLoadCommon;
// Métodos públicos de la API, agrupados en paths.
unauth: IAppLoadPathsRecord;
// Perfil del cliente actual. Se omite para los invitados.
user?: IApploadUserProfile;
// Métodos de la sesión autenticada. Se omiten para los invitados; el backend
// comprueba los permisos.
auth?: IAppLoadPathsRecord;
// Si las funciones del panel del vendedor están activadas en esta tienda.
seller_panel_enabled?: boolean;
// Clave de vista previa de productos para una cuenta con sesión iniciada y
// datos de vendedor.
// No publiques su valor; las interfaces para compradores no necesitan esta
// clave.
view_key?: string;
// Tiempo que tarda el backend en preparar Application Load, en segundos; solo
// con la depuración del proyecto activada.
// No incluye la serialización de la respuesta ni la transferencia por la red.
spent_total?: number;
// Tiempo de carga de init en el backend, en segundos. Solo con la depuración
// del proyecto activada.
spent_init?: number;
// Tiempo de carga del descubrimiento de la API pública, en segundos. Solo con
// la depuración del proyecto activada.
unauth_spent?: number;
// Tiempo de preparación del perfil y de auth, en segundos. Solo en depuración;
// cero para los invitados.
auth_spent?: number;
}
Qué construir con init
Cada campo enlaza con su referencia de datos, sus consumidores reales y las guías de componentes relacionadas.
page_data.init/api/apploadIdioma, monedas y unidades
Idiomas, monedas y unidades de medida, con nombres, formatos de visualización y valores predeterminados para cada idioma.
localestore.localesMainLanguageSwitcherselecciona el idioma; la tienda aplica su moneda y sus unidades predeterminadas a las selecciones actuales.currenciesstore.currenciesOpciones de moneda que lee
MainCurrencySwitcher.weightsstore.weightsOpciones de unidad de peso que lee
UnitSwitcher.lengthsstore.lengthsOpciones de unidad de longitud que lee
UnitSwitcher.shipping_countriesstore.init?.shipping_countriesLos países de envío de la tienda, nombrados en las condiciones de devolución de las páginas de producto.
Catálogo y búsqueda
Categorías, colecciones iniciales de productos, sugerencias de búsqueda y planes de suscripción.
catalogstore.catalogÁrbol de categorías que usan
CatalogHeaderyCategoryGroup.productsstore.productsProductos iniciales que leen
ProductGroup,ProductCardy componentes de producto comoHoverImageViewer.featuredstore.featuredRecomendaciones personalizadas según búsquedas y categorías anteriores. Los componentes de producto las leen con
collection="featured".sellersstore.init?.sellersDatos de los vendedores indexados por ID. Cada producto de Application Load identifica a su vendedor con
seller_id; el store de productos resuelve esa referencia cuando los componentes leen el producto.search_hintsstore.init?.search_hintsSugerencias localizadas que muestra
MainSearch.tariffsstore.tariffsColección de planes que lee
TariffCardspara mostrar componentesTariffCardindividuales.
Marca y metadatos de la página
Logotipos, el icono del sitio, los ajustes de visualización de la tienda y los metadatos SEO.
logosstore.init?.logosBrandLogosmuestra el tamaño de logotipo o el icono seleccionado.visual_settingsstore.init?.visual_settingsImágenes de las categorías del menú, número y orden de las categorías de inicio y otros ajustes de visualización de la tienda.
seostore.init?.seogetStorefrontSeo()prepara los metadatos deapp/pages/index.vue: el título, la descripción y las palabras clave usanuseSeoMeta(), y las etiquetas adicionales usanuseHead().
Contenido y contactos
Banners, eventos de la tienda, contactos de la empresa y enlaces sociales.
main_bannerstore.init?.main_bannerImágenes de banners que muestra
MainBanneren el idioma actual de la tienda.eventsstore.init?.eventsImágenes de eventos que muestra
EventsBlock, filtradas por idioma y poris_layout.contactstore.init?.contactContactos y datos de registro de la empresa que muestra
AboutPage.smstore.init?.smEnlaces sociales y textos localizados que muestra
SocialLinks.
Cliente y contadores
Estado de autenticación, saldo del monedero y contadores iniciales del carrito y de favoritos. El carrito completo y los datos de la cuenta se obtienen con endpoints de la API aparte.
is_authenticatedstore.isAuthenticatedstore.isAuthenticatedcontrola el descubrimiento autenticado y cambiaStorefrontAccountentre Iniciar sesión y el menú de perfil y monedero.walletstore.init?.walletWalletBalancemuestra el saldo en la moneda seleccionada, también en el modo compacto deStorefrontAccount.variablesstore.init?.variablesContadores iniciales de los botones del carrito y de favoritos, permiso de reserva y estados de contenido predeterminados.
Mapas e integraciones
Centro del mapa, clave pública del mapa y disponibilidad de la búsqueda de direcciones por coordenadas.
default_mapstore.init?.default_mapCoordenadas del centro del mapa predeterminadas.
geo_location_enabledstore.init?.geo_location_enabledIndica si está disponible la búsqueda de direcciones por coordenadas. Las sugerencias de texto dependen del país seleccionado.
public_keysstore.init?.public_keysmap_keycarga Yandex Maps para el mapa de entrega del carrito.
Los campos dependen de los ajustes de la tienda y de la sesión actual. Un campo puede faltar o una colección estar vacía. Los productos iniciales no sustituyen a un catálogo completo y paginado.
Usa los datos tras la inicialización
app/middleware/00.basklee.global.tsEl middleware global se ejecuta antes de cada página y espera a la inicialización.
Una vez cargados los datos, la navegación no repite la solicitud. Si la carga falla, el store registra el fallo y el middleware abre la página de error de la tienda con HTTP 503 y un botón Reintentar que recarga la página. Una dirección desconocida conserva su página 404. El middleware no muestra notificaciones por sí mismo.
Código fuente
import { abortNavigation, defineNuxtRouteMiddleware } from '#imports'; import { useBaskleeAppLoad } from '@/composables/useBaskleeAppLoad'; import { storefrontPageError } from '@/composables/useBaskleeMissingPage'; /** * Bootstrap precedes page setup. A failed Application Load opens the * storefront error page with HTTP 503 on every page; an unknown address keeps * its 404 page. */ export default defineNuxtRouteMiddleware(async (to) => { const { initialize, store } = useBaskleeAppLoad(); const locale = typeof to.query.locale === 'string' ? to.query.locale : ''; await initialize(locale); if (!to.matched.length) { return; } const error = storefrontPageError(store.status, false, ''); if (error) { return abortNavigation(error); } });app/composables/useBaskleeAppLoad.tsEl composable llama al cliente de API compartido, valida la respuesta de inicialización y pasa el resultado al store. El transporte del cliente reenvía las cookies que el backend establece durante un renderizado en el servidor.
Ofrece las acciones de inicializar, actualizar y reiniciar. Acceder a él sin más no inicia ninguna solicitud.
Código fuente
import { createError, usePinia, useResponseHeader } from '#imports'; import { computed } from 'vue'; import { storeToRefs } from 'pinia'; import { useBaskleeStore } from '@/stores/basklee'; import type { AppLoadFailure, AppLoadResult, } from '@/interfaces/basklee/transport'; import { useBaskleeApi } from '@/composables/useBaskleeApi'; import { appLoadRejectedLocale, appLoadResult, inspectAppLoad, } from '@/utils/baskleeAppLoad'; /** Transport and explicit actions. Calling this accessor does not start a request. */ export function useBaskleeAppLoad() { // SSR forwards the current request's domain, cookies and authorization to our own gateway. const store = useBaskleeStore(usePinia()); const refs = storeToRefs(store); const api = useBaskleeApi(); if (import.meta.server) { useResponseHeader('cache-control').value = 'private, no-store'; } const request = async ( signal: AbortSignal, locale = '', ): Promise<AppLoadResult> => { let received: { body: unknown; status: number; cookies: string[] } | undefined; try { received = await api.applicationLoad(signal, locale); } catch { throw createError({ message: 'Could not reach the marketplace API.', data: { kind: 'network', httpStatus: null, fields: [], } satisfies AppLoadFailure, }); } if (!received) { throw createError({ message: 'The API returned no response.', data: { kind: 'network', httpStatus: null, fields: [], } satisfies AppLoadFailure, }); } // A cookie that AppLoad sets during a server render (a new guest session // or CSRF token) is relayed to the browser by the shared API transport, // which also sends it with the later requests of the same render. const failure = inspectAppLoad(received.body, received.status); // An address with a language the storefront does not have (`?locale=xx`) // opens in the storefront's default language instead of the 503 page. if (failure && locale && appLoadRejectedLocale(failure)) { return request(signal); } if (failure) { throw createError({ message: 'Marketplace initialization failed.', data: failure, }); } return appLoadResult(received.body, received.status); }; return { store, data: refs.result, status: refs.status, error: computed(() => (store.failure ? { data: store.failure } : null)), initialize: (locale = '') => store.load((signal) => request(signal, locale)), refresh: () => store.load(request, true), // Called by the shared API client after HTTP 401 in a signed-in session. endSession: () => store.endSession(request), reset: () => store.reset(), }; }app/composables/useBaskleeApi.tsCrea los clientes de API compartidos de una aplicación Nuxt: uno para la sesión del navegador y uno para cada renderizado en el servidor. Los componentes envían solicitudes a los endpoints descubiertos en el navegador. Las páginas de producto, categoría, búsqueda, recomendados, blog y artículo también cargan sus primeros datos durante el renderizado en el servidor mediante
useBaskleeServerApi(), con las cookies del visitante, de modo que el HTML de la página ya contiene esos datos. El navegador reutiliza el resultado sin repetir la solicitud.Código fuente
import { useNuxtApp, usePinia, useRequestFetch, useRequestHeader, useResponseHeader, useRuntimeConfig, } from '#imports'; import { useBaskleeStore } from '@/stores/basklee'; import { useBaskleeSelectionsStore } from '@/stores/baskleeSelections'; import { useBaskleeAppLoad } from '@/composables/useBaskleeAppLoad'; import { BaskleeApi } from '@/utils/basklee/api'; import type { BaskleeApiRequest, BaskleeApiResponse, } from '@/utils/basklee/api'; import { createBaskleeCookieJar } from '@/utils/basklee/serverCookies'; import { nativeAppCookies, nativeAppOrigin, nativeAppRequest, } from '@/utils/basklee/nativeApp'; interface BaskleeClients { browser: BaskleeApi; server: BaskleeApi; } // One entry per Nuxt application: one browser session, or one server render. const clients = new WeakMap<object, BaskleeClients>(); function createClients(): BaskleeClients { const nuxt = useNuxtApp(); const store = useBaskleeStore(usePinia()); const selections = useBaskleeSelectionsStore(); const requestFetch = useRequestFetch(); // A server render sends the visitor's cookies and the cookies the backend // set earlier in the same render; see utils/basklee/serverCookies.ts. const jar = import.meta.server ? createBaskleeCookieJar(useRequestHeader('cookie')) : undefined; const responseCookies = import.meta.server ? useResponseHeader('set-cookie') : undefined; // The Android app sends its requests to the public storefront; see // utils/basklee/nativeApp.ts. Empty on the website. const appOrigin = nativeAppOrigin( useRuntimeConfig().public.baskleeAppOrigin, ); // Every cookie the backend sets during a server render reaches the // browser as its own Set-Cookie header, unchanged. function relay(cookies: string[]) { if (!responseCookies || !cookies.length) { return; } const existing = responseCookies.value; const existingCookies = Array.isArray(existing) ? [...existing] : []; if (existing && !Array.isArray(existing)) { existingCookies.push(String(existing)); } responseCookies.value = [...existingCookies, ...cookies]; } const transport = async ( path: string, request: BaskleeApiRequest, ): Promise<BaskleeApiResponse> => { if (appOrigin) { return nativeAppRequest(appOrigin, path, request); } let received: BaskleeApiResponse | undefined; // A server render's own API call copies the visitor's request headers. // A visitor who follows a link from another site arrives with // `Sec-Fetch-Site: cross-site` (and a form post with a foreign Origin); // the gateway's cross-site check would refuse the render's call and the // page would answer 503. The call comes from this server, so it is sent // as same-origin without the visitor's Origin. const headers = jar ? { ...request.headers, cookie: jar.header(), origin: '', 'sec-fetch-site': 'same-origin', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', } : request.headers; await requestFetch<unknown>(path, { // Nuxt 4.6 types the method per known server route; the gateway path // is a plain string, for which only 'get' type-checks. ofetch sends any // method as given, so the type alone is widened. method: request.method as 'get', headers, body: request.method === 'GET' ? undefined : request.data, query: request.method === 'GET' && !(request.data instanceof FormData) ? request.data : undefined, signal: request.signal, credentials: 'same-origin', cache: 'no-store', retry: 0, timeout: 35_000, ignoreResponseError: true, onResponse({ response }) { received = { body: response._data, status: response.status, cookies: import.meta.server ? response.headers.getSetCookie() : [], headers: { 'content-type': response.headers.get('content-type') ?? '', 'content-disposition': response.headers.get('content-disposition') ?? '', }, }; }, }); if (!received) { throw new Error('The API returned no response.'); } jar?.apply(received.cookies); relay(received.cookies); return received; }; const shared = { transport, endpoints: () => store.endpoints, cookies: () => jar ? jar.header() : appOrigin ? nativeAppCookies() : document.cookie, locale: () => store.localeCode, isSignedIn: () => store.isAuthenticated, // The customer's currency for orders and plan purchases (CURRENCY_REQUESTS). currency: () => selections.currencyId, }; return { // Components send their requests in the browser. During a server render // this client sends only Application Load, so a request started while // the page renders cannot outlive the render. browser: new BaskleeApi({ ...shared, canRequest: () => import.meta.client, // HTTP 401 ended the customer's session: show the guest storefront. // This never opens sign-in and never repeats the failed request. onSessionEnded: () => nuxt.runWithContext(() => useBaskleeAppLoad().endSession()), }), // Page data that the server render awaits; see useBaskleeServerData. // A failed server request leaves the page to the browser, which loads // the data again and handles an ended session there. server: new BaskleeApi(shared), }; } function useBaskleeClients() { const nuxt = useNuxtApp(); const existing = clients.get(nuxt); if (existing) { return existing; } const created = createClients(); clients.set(nuxt, created); return created; } export function useBaskleeApi() { return useBaskleeClients().browser; } /** * The client for page data loaded during a server render. It shares the * transport, endpoint discovery, cookies and CSRF handling with * `useBaskleeApi`. Use it through `useBaskleeServerData`, which * awaits the request before the page renders. */ export function useBaskleeServerApi() { return useBaskleeClients().server; }app/utils/basklee/api.tsSe encarga del arranque de Application Load y resuelve las solicitudes del navegador por
url_namea partir del descubrimiento actual. Lee el token CSRF actual en cada solicitud y evita renovaciones duplicadas. Un rechazo CSRF renueva el token para la siguiente acción y devuelve el error. El cliente vuelve a intentarlo de forma explícita; las solicitudes fallidas nunca se repiten automáticamente.Código fuente
import type { IAppLoadPathObject } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonPath'; import type { TMethod } from '@/interfaces/basklee/apiBase/TMethod'; export interface BaskleeApiResponse { body: unknown; status: number; cookies: string[]; headers?: Record<string, string>; } export type BaskleeApiData = Record<string, unknown> | FormData; export interface BaskleeApiRequest { method: TMethod; data: BaskleeApiData; headers: Record<string, string>; signal?: AbortSignal; } export type BaskleeTransport = ( path: string, request: BaskleeApiRequest, ) => Promise<BaskleeApiResponse>; /** * The texts of the field errors, each once: Basklee often repeats a * field's error for the whole form. */ export function fieldErrorText(fields: Record<string, unknown>) { return [...new Set(Object.values(fields).filter(Boolean))].join(' '); } export class BaskleeApiError extends Error { readonly kind: 'unavailable' | 'failed'; readonly fields: Record<string, string>; readonly status?: number; readonly data?: unknown; // Error codes of the answer, such as `sign_in` when Basklee asks the visitor // to sign in first. readonly codes: string[]; constructor( kind: 'unavailable' | 'failed', fields: Record<string, string> = {}, status?: number, data?: unknown, codes: string[] = [], ) { super(fieldErrorText(fields) || kind); this.kind = kind; this.fields = fields; this.status = status; this.data = data; this.codes = codes; } } /** * Requests whose amounts the backend counts in the customer's currency: an * order, a preorder and a plan purchase are priced and charged in it. The * client adds the selected currency to them (unless the caller set one). */ export const CURRENCY_REQUESTS = new Set([ 'orders_create', 'preorders_create', 'subscriptions_subscribe', 'subscriptions_renew', 'subscriptions_change_renew', 'subscriptions_change_tariff', 'subscriptions_change_option', ]); export class BaskleeApi { private renewal: Promise<void> | undefined; private sessionEnding: Promise<void> | undefined; private transport: BaskleeTransport; private endpoints: () => IAppLoadPathObject; private cookies: () => string; private locale: () => string; private canRequest: () => boolean; private isSignedIn: () => boolean; private currency: () => string | number | undefined; private onSessionEnded: (() => unknown) | undefined; constructor(options: { transport: BaskleeTransport; endpoints: () => IAppLoadPathObject; cookies: () => string; locale?: () => string; canRequest?: () => boolean; isSignedIn?: () => boolean; currency?: () => string | number | undefined; onSessionEnded?: () => unknown; }) { this.transport = options.transport; this.endpoints = options.endpoints; this.cookies = options.cookies; this.locale = options.locale ?? (() => ''); this.canRequest = options.canRequest ?? (() => true); this.isSignedIn = options.isSignedIn ?? (() => false); this.currency = options.currency ?? (() => undefined); this.onSessionEnded = options.onSessionEnded; } /** The guest refresh started by the latest HTTP 401, while it runs. */ get sessionEnd() { return this.sessionEnding; } applicationLoad(signal: AbortSignal, locale = '') { return this.send( '/api/appload', 'POST', { detalize_mode: 'light', ignore_cache: false, }, signal, locale, ); } async request<T>( name: string, data: BaskleeApiData, signal?: AbortSignal, params: Record<string, number> = {}, ): Promise<T> { return this.successData<T>( await this.requestResponse(name, data, signal, params), ); } async requestResponse( name: string, data: BaskleeApiData, signal?: AbortSignal, params: Record<string, number> = {}, ): Promise<BaskleeApiResponse> { if (!this.canRequest()) { throw new BaskleeApiError('unavailable'); } const discovered = Object.values(this.endpoints()) .flatMap((section) => Object.values(section)) .find((entry) => entry.url_name === name); const endpoint = discovered ?? (name === 'reload_customer_app' ? { target: 'api/reload_customer_app', methods: ['PATCH' as const] } : undefined); const method = endpoint?.methods[0]; let path = `/${endpoint?.target.replace(/^\/+/, '') ?? ''}`; path = path.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_, key: string) => { const value = params[key]; if (!Number.isSafeInteger(value) || Number(value) <= 0) { throw new BaskleeApiError('unavailable'); } return String(value); }); if ( !endpoint || !method || !/^\/api\/[a-zA-Z0-9_/-]+(?:\.png)?$/.test(path) ) { throw new BaskleeApiError('unavailable'); } if (method === 'GET' && data instanceof FormData) { throw new BaskleeApiError('unavailable'); } const currency = Number(this.currency()); if ( CURRENCY_REQUESTS.has(name) && !(data instanceof FormData) && data.currency === undefined && Number.isSafeInteger(currency) && currency > 0 ) { data = { ...data, currency }; } const protectedRequest = method !== 'GET'; if (protectedRequest && !this.csrfToken()) { await this.renewCsrf(); } signal?.throwIfAborted(); const response = await this.send(path, method, data, signal); const body = response.body as { page_data?: { csrf?: boolean }; } | null; // A CSRF rejection: Django views answer 419, API endpoints answer 403 // with page_data.csrf set to false. The request is not repeated. const csrfRejected = response.status === 419 || (response.status === 403 && body?.page_data?.csrf === false); // Renew for the next explicit action and retain this request's rejection. if (protectedRequest && csrfRejected) { await this.renewCsrf(); signal?.throwIfAborted(); } this.detectSessionEnd(response); signal?.throwIfAborted(); return response; } /* * The backend answers HTTP 401 when the request has no signed-in session: * an authentication-required endpoint without a customer ({ auth: false }), * or a session the backend rejected and whose cookies it deleted. * A 401 while the application still shows a customer means the session * ended. One handler call serves concurrent failures; a guest 401, 403 and * CSRF rejection are ordinary request errors. */ private detectSessionEnd(response: BaskleeApiResponse) { if ( response.status !== 401 || this.sessionEnding || !this.onSessionEnded || !this.isSignedIn() ) { return; } let ending: Promise<void>; try { ending = Promise.resolve(this.onSessionEnded()).then(() => undefined); } catch (error) { ending = Promise.reject(error); } // The failed request reports its own error; the refresh has its own state. this.sessionEnding = ending .catch(() => undefined) .finally(() => { this.sessionEnding = undefined; }); } private csrfToken() { return this.cookies().match(/(?:^|;\s*)csrftoken=([^;]*)/)?.[1] ?? ''; } private localizedPath(path: string, requestedLocale = '') { const locale = (requestedLocale || this.locale()).trim(); if (!locale) { return path; } const separator = path.includes('?') ? '&' : '?'; return `${path}${separator}lang=${encodeURIComponent(locale)}`; } private async renewCsrf() { if (!this.renewal) { this.renewal = this.send('/api/csrf_renew', 'POST', {}) .then((response) => { this.detectSessionEnd(response); this.successData(response); if (!this.csrfToken()) { throw new BaskleeApiError('failed'); } }) .finally(() => { this.renewal = undefined; }); } await this.renewal; } private send( path: string, method: TMethod, data: BaskleeApiData, signal?: AbortSignal, locale = '', ) { const headers: Record<string, string> = { Accept: 'application/json', ...(data instanceof FormData ? {} : { 'Content-Type': 'application/json' }), }; const token = this.csrfToken(); if (token) { headers['X-CSRFToken'] = token; } return this.transport(this.localizedPath(path, locale), { method, data, headers, signal, }); } private successData<T>(response: BaskleeApiResponse): T { const body = response.body as { form_errors?: unknown; success_message?: unknown; page_data?: T; } | null; if ( response.status < 200 || response.status >= 300 || body?.form_errors !== null || typeof body.success_message !== 'string' || !body.success_message ) { const fields = Object.fromEntries( Object.entries(body?.form_errors ?? {}).map(([name, entries]) => [ name, Array.isArray(entries) ? entries.map((entry) => String(entry?.message ?? '')).join(' ') : '', ]), ); const codes = Object.values(body?.form_errors ?? {}) .flatMap((entries) => (Array.isArray(entries) ? entries : [])) .map((entry) => String(entry?.code ?? '')) .filter(Boolean); throw new BaskleeApiError( 'failed', fields, response.status, body?.page_data, codes, ); } return body.page_data as T; } }app/stores/basklee.tsuseBaskleeStore()- Accesor del componente para los stores coordinados que se muestran abajo.
store.result- Resultado de la carga: cuerpo de la respuesta, estado HTTP y hora de obtención.
store.result?.response- Cuerpo completo de la respuesta de la API.
store.data- Datos de la aplicación de la respuesta de la API.
store.init- Datos iniciales de la tienda. Los enlaces de arriba llevan a cada campo, a su componente y al código fuente.
store.profile- Perfil del cliente, cuando la respuesta lo incluye.
useBaskleeStore()guarda la respuesta de Application Load, el estado de carga, el perfil, el monedero y el descubrimiento de endpoints. Los componentes leen las selecciones, los datos del catálogo, los productos y el estado de navegación a través de los hooks de store de su dominio. Coordina la actualización, el reinicio y los cambios de sesión entre los stores más pequeños.Código fuente
import type { IApploadUserProfile } from '@/interfaces/basklee/appBase/IApploadUserProfile'; import { computed, ref, shallowRef, hasInjectionContext, inject, provide, } from 'vue'; import type { InjectionKey, Ref } from 'vue'; import type { Pinia } from 'pinia'; import { defineStore, getActivePinia, storeToRefs } from 'pinia'; import { useBaskleeSelections } from '@/stores/baskleeSelections'; import { useBaskleeBrowse } from '@/stores/baskleeBrowse'; import { useBaskleeCatalog } from '@/stores/baskleeCatalog'; import { useBaskleeProducts } from '@/stores/baskleeProducts'; import { attachBaskleeDomainStores, registerBaskleeDomainResolver, registerBaskleeDomainStores, releaseBaskleeDomainStores, } from '@/stores/baskleeDomainAccess'; import { guestAppLoadResult, guestProduct, } from '@/utils/basklee/guestSession'; import type { IProduct } from '@/interfaces/basklee/products/IProduct'; import type { AppLoadFailure, AppLoadResult, AppLoadLoader, AppLoadStatus, IAppLoadPathObject, } from '@/interfaces/basklee'; function forwardedState<T>(source: Ref<T>) { return computed({ get: () => source.value, set: (value: T) => { source.value = value; }, }); } /** One instance per Nuxt SSR request; @pinia/nuxt hydrates it into the browser. */ function createStoreState(scope: string, pinia: Pinia) { const result = shallowRef<AppLoadResult | null>(null); const status = ref<AppLoadStatus>('idle'); const failure = shallowRef<AppLoadFailure | null>(null); const isReady = computed( () => status.value === 'success' && result.value !== null, ); const data = computed(() => result.value?.response.page_data ?? null); const init = computed(() => data.value?.init ?? null); const profile = computed(() => data.value?.user ?? null); const isAuthenticated = computed(() => init.value?.is_authenticated ?? false); const selections = useBaskleeSelections( scope, pinia, init, ); const selectionRefs = storeToRefs(selections); const { locales, currencies, weights, lengths, currentLocale, currentCurrency, } = selectionRefs; const localeCode = forwardedState(selectionRefs.localeCode); const currencyId = forwardedState(selectionRefs.currencyId); const weightId = forwardedState(selectionRefs.weightId); const lengthId = forwardedState(selectionRefs.lengthId); const { setLocale, setCurrency, setUnit, } = selections; const catalogState = useBaskleeCatalog( scope, pinia, init, ); const catalogRefs = storeToRefs(catalogState); const { catalog, tariffs, storeTariffs, products, featured, catalogRoots, catalogShortcuts, catalogCategories, } = catalogRefs; const catalogSnapshot = forwardedState(catalogRefs.catalogSnapshot); const tariffsSnapshot = forwardedState(catalogRefs.tariffsSnapshot); const { setCatalogTree, setTariffs, setStoreTariffs, getTariff, getCatalogCategory, getCatalogProducts, } = catalogState; const productState = useBaskleeProducts( scope, pinia, init, products, featured, ); const productRefs = storeToRefs(productState); const { homeProductSections, counters, } = productRefs; const homeNewProductIds = forwardedState(productRefs.homeNewProductIds); const productSecondaryVariants = forwardedState( productRefs.productSecondaryVariants, ); const productUpdates = forwardedState(productRefs.productUpdates); const productRequests = forwardedState(productRefs.productRequests); const { setHomeNewProducts, getProducts, getProduct, setProduct, patchProductState, getProductRequest, setProductRequest, getSecondaryVariants, synchronizeProductCart, setSecondaryVariants, getProductAvailability, setProductCounters, } = productState; const browse = useBaskleeBrowse( scope, pinia, init, ); const browseRefs = storeToRefs(browse); const searchQuery = forwardedState(browseRefs.searchQuery); const searchFacets = forwardedState(browseRefs.searchFacets); const searchFilters = forwardedState(browseRefs.searchFilters); const blogPosts = forwardedState(browseRefs.blogPosts); const { setSearchFacets, preserveSearchFacets, setSearchFilters, setBlogPosts, } = browse; registerBaskleeDomainStores(pinia, scope, { selections, catalog: catalogState, products: productState, browse, }); function patchProfile(value: Partial<IApploadUserProfile>) { const current = result.value; const page = current?.response.page_data; if (!current || !page?.user || !isAuthenticated.value) { return; } result.value = { ...current, response: { ...current.response, page_data: { ...page, user: { ...page.user, ...value } }, }, }; } function patchWallet( wallet: NonNullable<NonNullable<typeof init.value>['wallet']>, ) { const current = result.value; const page = current?.response.page_data; if (!current || !page?.init || !isAuthenticated.value) { return; } result.value = { ...current, response: { ...current.response, page_data: { ...page, init: { ...page.init, wallet } }, }, }; } function applyResult(value: AppLoadResult) { catalogState.reset(); productState.reset(); browse.resetResults(); result.value = value; status.value = 'success'; failure.value = null; selections.reconcile(); } const publicEndpoints = computed(() => data.value?.unauth.paths ?? {}); const authenticatedEndpoints = computed(() => isAuthenticated.value ? (data.value?.auth?.paths ?? {}) : {}, ); const endpoints = computed<IAppLoadPathObject>(() => { const merged: IAppLoadPathObject = {}; for (const groups of [ publicEndpoints.value, authenticatedEndpoints.value, ]) { for (const [section, paths] of Object.entries(groups)) { merged[section] = { ...merged[section], ...paths }; } } return merged; }); const getEndpoint = (section: string, name: string) => endpoints.value[section]?.[name]; // These belong to this store instance, never serialized state or a module-level cache. let pending: Promise<void> | null = null; let controller: AbortController | null = null; let generation = 0; function reset() { generation++; controller?.abort(); controller = null; pending = null; result.value = null; catalogState.reset(); productState.reset(); browse.reset(); selections.reset(); failure.value = null; status.value = 'idle'; } /* * The shared API client calls this when a request answers HTTP 401 while * this store still shows a signed-in customer. The signed-in data is removed * at once, so the header and account pages show the guest state, and the * guest Application Load replaces the remaining snapshot in the background. * A guest store is left unchanged. */ function endSession(loader: AppLoadLoader): Promise<void> { if (!isAuthenticated.value || !result.value) { return pending ?? Promise.resolve(); } showGuestSnapshot(result.value); return load(loader, true, true); } function showGuestSnapshot(current: AppLoadResult) { const guestProducts = (items: Record<number, IProduct>) => Object.fromEntries( Object.entries(items).map(([id, item]) => [id, guestProduct(item)]), ); generation++; controller?.abort(); controller = null; pending = null; result.value = guestAppLoadResult(current); productState.clearSession(); productUpdates.value = { products: guestProducts(productUpdates.value.products), featured: guestProducts(productUpdates.value.featured), }; for (const state of Object.values(productSecondaryVariants.value)) { for (const variant of state.data?.variants ?? []) { variant.product = guestProduct(variant.product); } } } /* * `preserve` keeps the current snapshot visible while the replacement loads. * It is used only after `endSession` has already removed signed-in data. */ function load( loader: AppLoadLoader, force = false, preserve = false, ): Promise<void> { if (pending) { return pending; } // Reuse both SSR success and failure on hydration/navigation; retry is explicit. if (!force && status.value !== 'idle') { return Promise.resolve(); } const current = ++generation; controller = new AbortController(); const signal = controller.signal; if (!preserve) { catalogState.reset(); productState.reset(); browse.resetResults(); result.value = null; failure.value = null; status.value = 'pending'; } pending = Promise.resolve() .then(() => loader(signal)) .then((value) => { if (current !== generation) { return; } applyResult(value); }) .catch((error: unknown) => { if (current !== generation) { return; } const detail = error && typeof error === 'object' && 'data' in error ? error.data : null; const known = detail && typeof detail === 'object' && 'kind' in detail && ['http', 'validation', 'invalid-response', 'network'].includes( String(detail.kind), ); failure.value = known ? { kind: detail.kind as AppLoadFailure['kind'], httpStatus: 'httpStatus' in detail && typeof detail.httpStatus === 'number' ? detail.httpStatus : null, fields: 'fields' in detail && Array.isArray(detail.fields) ? detail.fields.filter( (field): field is string => typeof field === 'string', ) : [], } : { kind: 'network', httpStatus: null, fields: [] }; result.value = null; status.value = 'error'; }) .finally(() => { if (current !== generation) { return; } pending = null; controller = null; }); return pending; } function disposeChildren() { selections.$dispose(); catalogState.$dispose(); productState.$dispose(); browse.$dispose(); } return { result, status, failure, isReady, data, init, profile, patchProfile, patchWallet, isAuthenticated, locales, currencies, catalog, catalogSnapshot, setCatalogTree, catalogRoots, catalogShortcuts, catalogCategories, products, tariffs, tariffsSnapshot, setTariffs, storeTariffs, setStoreTariffs, featured, homeNewProductIds, homeProductSections, setHomeNewProducts, weights, lengths, localeCode, currencyId, weightId, lengthId, searchQuery, searchFacets, searchFilters, blogPosts, setSearchFacets, preserveSearchFacets, setSearchFilters, setBlogPosts, currentLocale, currentCurrency, setLocale, setCurrency, setUnit, getProducts, getTariff, getProduct, productUpdates, productRequests, getProductRequest, setProductRequest, counters, setProductCounters, setProduct, patchProductState, synchronizeProductCart, productSecondaryVariants, getSecondaryVariants, setSecondaryVariants, getProductAvailability, getCatalogCategory, getCatalogProducts, applyResult, publicEndpoints, authenticatedEndpoints, endpoints, getEndpoint, load, endSession, reset, disposeChildren, }; } type BaskleeStore = ReturnType<typeof createBaskleeStore>; const storeScope: InjectionKey<BaskleeStore> = Symbol('basklee:store'); const wrappedStores = new WeakSet<object>(); // Scoped previews use another instance in the same Pinia, never another global app. export function provideBaskleeStore(store: BaskleeStore) { provide(storeScope, store); } export function createBaskleeStore(id: string, pinia: Pinia) { const store = defineStore(id, () => createStoreState(id, pinia))(pinia); attachBaskleeDomainStores(store, pinia, id); if (!wrappedStores.has(store)) { const dispose = store.$dispose.bind(store); store.$dispose = () => { store.disposeChildren(); dispose(); releaseBaskleeDomainStores(store, pinia, id); for (const key of [ id, `${id}:selections`, `${id}:catalog`, `${id}:products`, `${id}:browse`, ]) { delete pinia.state.value[key]; } }; wrappedStores.add(store); } return store; } export const useBaskleeStore = Object.assign( (pinia?: Pinia | null) => { const scoped = hasInjectionContext() ? inject(storeScope, null) : null; if (pinia) { return createBaskleeStore('basklee', pinia); } if (scoped) { return scoped; } return createBaskleeStore('basklee', getActivePinia()!); }, { $id: 'basklee' }, ); registerBaskleeDomainResolver( () => useBaskleeStore(), );app/stores/baskleeSelections.tsGuarda el idioma, la moneda, la unidad de peso y la unidad de longitud seleccionados. Un cambio de idioma selecciona sus valores predeterminados configurados; una actualización de Application Load conserva las opciones que siguen disponibles.
Código fuente
import { computed, ref } from 'vue'; import type { ComputedRef } from 'vue'; import { defineStore } from 'pinia'; import type { Pinia } from 'pinia'; import { resolveBaskleeDomain } from '@/stores/baskleeDomainAccess'; import '@/stores/basklee'; import type { IAppLoadCommon } from '@/interfaces/basklee/appBase/IAppLoadCommon'; /** Customer choices shared by the storefront's language, currency and unit controls. */ export function useBaskleeSelections( scope: string, pinia: Pinia, init: ComputedRef<IAppLoadCommon | null>, ) { return defineStore(`${scope}:selections`, () => { const localeCode = ref(''); const currencyId = ref(''); const weightId = ref(''); const lengthId = ref(''); const locales = computed(() => init.value?.locale ?? {}); const currencies = computed(() => init.value?.currencies ?? {}); const weights = computed(() => init.value?.weights ?? {}); const lengths = computed(() => init.value?.lengths ?? {}); const currentLocale = computed(() => findLocale(localeCode.value)?.[1]); const currentCurrency = computed(() => currencies.value[currencyId.value]); function findLocale(code: string) { return Object.entries(locales.value).find( ([key, value]) => (value.code?.trim() || key).toLowerCase() === code.trim().toLowerCase(), ); } function unitId(values: Record<string, unknown>, preferred?: number | string) { const id = String(preferred ?? ''); return Object.hasOwn(values, id) ? id : (Object.keys(values)[0] ?? ''); } function availableCurrency(preferred?: number | string) { const id = String(preferred ?? ''); if (currencies.value[id]?.allowed_select) { return id; } return Object.keys(currencies.value).find( (key) => currencies.value[key]?.allowed_select, ) ?? ''; } function setLocale(code: string) { const entry = findLocale(code); if (!entry) { return; } localeCode.value = entry[1].code?.trim() || entry[0]; currencyId.value = availableCurrency(entry[1].currency); weightId.value = unitId(weights.value, entry[1].weight); lengthId.value = unitId(lengths.value, entry[1].length); } function setCurrency(id: string) { if (currencies.value[id]?.allowed_select) { currencyId.value = id; } } function setUnit(kind: 'weights' | 'lengths', id: string) { const values = kind === 'weights' ? weights.value : lengths.value; if (!Object.hasOwn(values, id)) { return; } if (kind === 'weights') { weightId.value = id; } else { lengthId.value = id; } } function reconcile() { const selected = findLocale(localeCode.value) ?? Object.entries(locales.value)[0]; localeCode.value = selected?.[1].code?.trim() || selected?.[0] || ''; currencyId.value = availableCurrency( currencies.value[currencyId.value]?.allowed_select ? currencyId.value : selected?.[1].currency, ); weightId.value = unitId( weights.value, Object.hasOwn(weights.value, weightId.value) ? weightId.value : selected?.[1].weight, ); lengthId.value = unitId( lengths.value, Object.hasOwn(lengths.value, lengthId.value) ? lengthId.value : selected?.[1].length, ); } function reset() { localeCode.value = ''; currencyId.value = ''; weightId.value = ''; lengthId.value = ''; } return { localeCode, currencyId, weightId, lengthId, locales, currencies, weights, lengths, currentLocale, currentCurrency, setLocale, setCurrency, setUnit, reconcile, reset, }; })(pinia); } /** Access the selection store associated with the current storefront scope. */ export function useBaskleeSelectionsStore() { return resolveBaskleeDomain<ReturnType<typeof useBaskleeSelections>>( 'selections', ); }app/stores/baskleeCatalog.tsLee las colecciones iniciales de categorías, productos y planes de Application Load. Las solicitudes correctas del catálogo y de planes pueden sustituir sus listas hasta la siguiente actualización.
Código fuente
import { computed, shallowRef } from 'vue'; import type { ComputedRef } from 'vue'; import { defineStore } from 'pinia'; import type { Pinia } from 'pinia'; import { resolveBaskleeDomain } from '@/stores/baskleeDomainAccess'; import '@/stores/basklee'; import type { IAppLoadCommon } from '@/interfaces/basklee/appBase/IAppLoadCommon'; import { navigationCatalogCategories, findCatalogCategory, catalogRepresentatives, } from '@/utils/basklee/catalog'; import { resolveAppLoadProducts } from '@/utils/basklee/productSeller'; /** * Application Load collections and the later catalog and tariff responses. * `storeTariffs` is every plan the storefront sells; the subscriptions page * and its dialogs read it. `tariffs` is what the plan pages show: the same * list, or a search result or one plan set with `setTariffs`. * `usedSubscriptions` holds the subscription records the signed-in customer * already had, for the profile that loaded them; a new Application Load * keeps it, another profile ignores it. */ export function useBaskleeCatalog( scope: string, pinia: Pinia, init: ComputedRef<IAppLoadCommon | null>, ) { return defineStore(`${scope}:catalog`, () => { const catalogSnapshot = shallowRef<NonNullable<IAppLoadCommon['catalog']>>(); const tariffsSnapshot = shallowRef<NonNullable<IAppLoadCommon['tariffs']>>(); const storeTariffsSnapshot = shallowRef<NonNullable<IAppLoadCommon['tariffs']>>(); const usedSubscriptions = shallowRef<{ profile: number; ids: number[] }>(); const catalog = computed( () => catalogSnapshot.value ?? init.value?.catalog ?? [], ); const storeTariffs = computed( () => storeTariffsSnapshot.value ?? init.value?.tariffs ?? null, ); const tariffs = computed( () => tariffsSnapshot.value ?? storeTariffs.value, ); const products = computed(() => resolveAppLoadProducts(init.value?.products, init.value?.sellers), ); const featured = computed(() => resolveAppLoadProducts(init.value?.featured, init.value?.sellers), ); const catalogRoots = computed(() => navigationCatalogCategories(catalog.value)); const catalogShortcuts = computed(() => catalogRoots.value.filter((category) => category.separate_menu), ); const catalogCategories = computed(() => { const categories = catalogRoots.value.filter( (category) => !category.separate_menu, ); return categories.length ? categories : catalogRoots.value; }); function setCatalogTree(tree: NonNullable<IAppLoadCommon['catalog']>) { catalogSnapshot.value = tree; } /** A search result or one plan: only the plan pages show it. */ function setTariffs(value: NonNullable<IAppLoadCommon['tariffs']>) { tariffsSnapshot.value = value; } /** The complete plan list of the storefront, loaded after Application Load. */ function setStoreTariffs(value: NonNullable<IAppLoadCommon['tariffs']>) { storeTariffsSnapshot.value = value; tariffsSnapshot.value = undefined; } /** The records the customer had, see `tariffUsedSubscriptions`. */ function setUsedSubscriptions(profile: number, ids: number[]) { usedSubscriptions.value = { profile, ids }; } /** Those records for this profile; undefined until they are loaded. */ function usedSubscriptionsOf(profile: number | undefined) { return usedSubscriptions.value && usedSubscriptions.value.profile === profile ? usedSubscriptions.value.ids : undefined; } function getTariff(id: number) { return tariffs.value?.data.find((tariff) => tariff.id === id); } function getCatalogCategory(id: number) { return findCatalogCategory(catalog.value, id); } function getCatalogProducts(categoryId: number) { return catalogRepresentatives( getCatalogCategory(categoryId), products.value, featured.value, ); } function reset() { catalogSnapshot.value = undefined; tariffsSnapshot.value = undefined; storeTariffsSnapshot.value = undefined; } return { catalogSnapshot, tariffsSnapshot, storeTariffsSnapshot, usedSubscriptions, catalog, tariffs, storeTariffs, products, featured, catalogRoots, catalogShortcuts, catalogCategories, setCatalogTree, setTariffs, setStoreTariffs, setUsedSubscriptions, usedSubscriptionsOf, getTariff, getCatalogCategory, getCatalogProducts, reset, }; })(pinia); } /** Access the catalog store associated with the current storefront scope. */ export function useBaskleeCatalogStore() { return resolveBaskleeDomain<ReturnType<typeof useBaskleeCatalog>>( 'catalog', ); }app/stores/baskleeProducts.tsGuarda los cambios de productos, las variantes secundarias, los grupos de productos de inicio y los contadores del carrito y de favoritos. Las acciones confirmadas actualizan estos valores; una actualización de Application Load los borra.
Código fuente
import { computed, ref } from 'vue'; import type { ComputedRef } from 'vue'; import { defineStore } from 'pinia'; import type { Pinia } from 'pinia'; import { resolveBaskleeDomain } from '@/stores/baskleeDomainAccess'; import '@/stores/basklee'; import type { IAppLoadCommon } from '@/interfaces/basklee/appBase/IAppLoadCommon'; import type { IProduct, IProductSearchSeller, } from '@/interfaces/basklee/products/IProduct'; import type { IProductSecondaryVariantState } from '@/interfaces/basklee/products/IProductSecondaryVariantRequest'; import { homeProductSections as groupHomeProducts } from '@/utils/basklee/homeContent'; import { productAvailability } from '@/utils/basklee/productAvailability'; import { productWithSellerPermission } from '@/utils/basklee/productSeller'; /** Products shared by cards, cart actions and variant selectors. */ export function useBaskleeProducts( scope: string, pinia: Pinia, init: ComputedRef<IAppLoadCommon | null>, products: ComputedRef<IProduct[]>, featured: ComputedRef<IProduct[]>, ) { return defineStore(`${scope}:products`, () => { const homeNewProductIds = ref<number[] | null>(null); const homeProductSections = computed(() => groupHomeProducts(products.value, featured.value, homeNewProductIds.value), ); function setHomeNewProducts( items: IProduct[], sellers: IProductSearchSeller[] = [], ) { if (!init.value) { return; } for (const product of items) { setProduct(product, 'products', sellers); } homeNewProductIds.value = items.map((product) => product.id); } const productSecondaryVariants = ref< Record<string, IProductSecondaryVariantState> >({}); const productCounters = ref<{ c_cart_positions?: number; c_wishlist?: number; }>({}); const counters = computed(() => ({ ...init.value?.variables, ...productCounters.value, })); function setProductCounters(values: { c_cart_positions?: number; c_wishlist?: number; }) { productCounters.value = { ...productCounters.value, ...values }; } const productUpdates = ref<{ products: Record<number, IProduct>; featured: Record<number, IProduct>; }>({ products: {}, featured: {} }); // Variant targets the host is loading for a card; see useBaskleeProductVariants. const productRequests = ref< Record<number, 'loading' | 'failed'> >({}); function getProducts(collection: 'products' | 'featured' = 'products') { return collection === 'featured' ? featured.value : products.value; } function getProduct( id: number, collection: 'products' | 'featured' = 'products', ) { return ( productUpdates.value[collection][id] ?? getProducts(collection).find((product) => product.id === id) ); } function setProduct( product: IProduct, collection: 'products' | 'featured' = 'products', sellers: IProductSearchSeller[] = [], ) { if (init.value && Number.isInteger(product.id) && product.id > 0) { productUpdates.value[collection][product.id] = productWithSellerPermission(product, sellers); } } function patchProductState( id: number, patch: Partial< Pick< IProduct, | 'cart_counts' | 'whishlist_id' | 'subscription_id' | 'c_real_left' | 'seller' > >, ) { for (const collection of ['products', 'featured'] as const) { const product = getProduct(id, collection); if (product) { setProduct({ ...product, ...patch }, collection); } } for (const state of Object.values(productSecondaryVariants.value)) { for (const variant of state.data?.variants ?? []) { if (variant.product.id === id) { variant.product = { ...variant.product, ...patch }; } } } } function getProductRequest(id: number) { return productRequests.value[id]; } function setProductRequest(id: number, state?: 'loading' | 'failed') { if (!Number.isInteger(id) || id <= 0) { return; } if (state) { productRequests.value[id] = state; } else { delete productRequests.value[id]; } } function getSecondaryVariants( productGroup: number, mainVariantValue: number, ) { return productSecondaryVariants.value[ `${productGroup}:${mainVariantValue}` ]; } function synchronizeProductCart(items: IProduct[]) { const counts = new Map( items.map((item) => [item.id, item.cart_counts ?? null]), ); for (const collection of ['products', 'featured'] as const) { const cached = new Map([ ...getProducts(collection).map((item) => [item.id, item] as const), ...Object.values(productUpdates.value[collection]).map( (item) => [item.id, item] as const, ), ]); for (const product of cached.values()) { productUpdates.value[collection][product.id] = { ...product, cart_counts: counts.get(product.id) ?? null, }; } } for (const state of Object.values(productSecondaryVariants.value)) { for (const variant of state.data?.variants ?? []) { variant.product = { ...variant.product, cart_counts: counts.get(variant.product.id) ?? null, }; } } } function setSecondaryVariants( productGroup: number, mainVariantValue: number, state: IProductSecondaryVariantState, ) { if ( init.value && Number.isInteger(productGroup) && productGroup > 0 && Number.isInteger(mainVariantValue) && mainVariantValue > 0 ) { productSecondaryVariants.value[`${productGroup}:${mainVariantValue}`] = state; } } function getProductAvailability( id: number, collection: 'products' | 'featured' = 'products', ) { const product = getProduct(id, collection); return productAvailability(product, init.value?.variables?.allow_preorder); } function resetHome() { homeNewProductIds.value = null; } function clearSession() { productRequests.value = {}; productCounters.value = {}; } function reset() { resetHome(); productSecondaryVariants.value = {}; productUpdates.value = { products: {}, featured: {} }; clearSession(); } return { homeNewProductIds, homeProductSections, setHomeNewProducts, productSecondaryVariants, productCounters, counters, setProductCounters, productUpdates, productRequests, getProducts, getProduct, setProduct, patchProductState, getProductRequest, setProductRequest, getSecondaryVariants, synchronizeProductCart, setSecondaryVariants, getProductAvailability, clearSession, reset, }; })(pinia); } /** Access the product store associated with the current storefront scope. */ export function useBaskleeProductsStore() { return resolveBaskleeDomain<ReturnType<typeof useBaskleeProducts>>( 'products', ); }app/stores/baskleeBrowse.tsGuarda el texto de búsqueda, los filtros seleccionados, las opciones de búsqueda y las entradas del blog. Las solicitudes de búsqueda y del blog rellenan estos valores; una actualización de Application Load borra los resultados y conserva el texto de búsqueda.
Código fuente
import { ref, shallowRef } from 'vue'; import type { ComputedRef } from 'vue'; import { defineStore } from 'pinia'; import type { Pinia } from 'pinia'; import { resolveBaskleeDomain } from '@/stores/baskleeDomainAccess'; import '@/stores/basklee'; import type { IAppLoadCommon } from '@/interfaces/basklee/appBase/IAppLoadCommon'; import type { IBlogPostPreview } from '@/interfaces/basklee/blog/IBlogPostPreview'; import type { IProductSearchFacets, ProductFacetSelection, } from '@/interfaces/basklee/products/IProductSearchFacets'; import { cloneSearchFilters, initialSearchFacets, } from '@/utils/basklee/searchFilters'; /** Search choices and journal results loaded after Application Load. */ export function useBaskleeBrowse( scope: string, pinia: Pinia, init: ComputedRef<IAppLoadCommon | null>, ) { return defineStore(`${scope}:browse`, () => { const searchQuery = ref(''); const searchFacets = shallowRef<IProductSearchFacets | null>(null); const searchFilters = ref<ProductFacetSelection>({}); const blogPosts = shallowRef<IBlogPostPreview[]>([]); function setSearchFacets(value: IProductSearchFacets | null) { searchFacets.value = value; } function preserveSearchFacets(value: IProductSearchFacets) { searchFacets.value = initialSearchFacets(searchFacets.value, value); } function setSearchFilters(value: ProductFacetSelection) { const selected = cloneSearchFilters(value); if (init.value?.visual_settings?.single_seller_mode) { delete selected.product_owner; } searchFilters.value = selected; } function setBlogPosts(value: IBlogPostPreview[]) { blogPosts.value = [...value]; } function resetResults() { searchFacets.value = null; searchFilters.value = {}; blogPosts.value = []; } function reset() { resetResults(); searchQuery.value = ''; } return { searchQuery, searchFacets, searchFilters, blogPosts, setSearchFacets, preserveSearchFacets, setSearchFilters, setBlogPosts, resetResults, reset, }; })(pinia); } /** Access the browse store associated with the current storefront scope. */ export function useBaskleeBrowseStore() { return resolveBaskleeDomain<ReturnType<typeof useBaskleeBrowse>>('browse'); }app/stores/baskleeDomainAccess.tsConecta cada hook de store de funciones con la tienda actual o con la vista previa de la documentación. Mantiene separadas las solicitudes al servidor y los datos de la vista previa.
Código fuente
import type { Pinia } from 'pinia'; export type BaskleeDomain = 'selections' | 'catalog' | 'products' | 'browse'; type DomainStores = Record<BaskleeDomain, unknown>; const storesByScope = new WeakMap<Pinia, Map<string, DomainStores>>(); const storesByFacade = new WeakMap<object, DomainStores>(); let resolveFacade: (() => object) | undefined; export function registerBaskleeDomainResolver(resolver: () => object) { resolveFacade = resolver; } export function registerBaskleeDomainStores( pinia: Pinia, scope: string, stores: DomainStores, ) { const scopes = storesByScope.get(pinia) ?? new Map<string, DomainStores>(); scopes.set(scope, stores); storesByScope.set(pinia, scopes); } export function attachBaskleeDomainStores( facade: object, pinia: Pinia, scope: string, ) { const stores = storesByScope.get(pinia)?.get(scope); if (!stores) { throw new Error(`Missing Basklee stores for ${scope}.`); } storesByFacade.set(facade, stores); } export function releaseBaskleeDomainStores( facade: object, pinia: Pinia, scope: string, ) { storesByFacade.delete(facade); storesByScope.get(pinia)?.delete(scope); } export function resolveBaskleeDomain<T>(domain: BaskleeDomain): T { const facade = resolveFacade?.(); const stores = facade && storesByFacade.get(facade); if (!stores) { throw new Error('The Basklee store has not been initialized.'); } return stores[domain] as T; }app/interfaces/basklee/appBase/IAppLoad.tsIAppLoaddescribe init, unauth, user y auth.Los tipos anidados se importan de archivos vecinos; los campos comunes de init se definen en app/interfaces/basklee/appBase/IAppLoadCommon.ts.
app/interfaces/basklee/appBase/IAppLoadCommon.tsIAppLoadCommonenumera los campos de init y sus interfaces anidadas: idiomas, monedas, unidades, banners, catálogo y otros datos iniciales.Código fuente
Ajustes compartidos de la tienda y contenido inicial.
app/interfaces/basklee/appBase/IAppLoadCommon.tsimport type { IAppLoadCommonLocale } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonLocale'; import type { IAppLoadCommonCurrency } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonCurrency'; import type { IAppLoadCommonUnit } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonUnit'; import type { IAppLoadCommonLogos } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonLogos'; import type { IGeoCoordinates } from '@/interfaces/basklee/shared/IGeoCoordinates'; import type { IAppLoadCommonSeo } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonSEO'; import type { IAppLoadCommonSocial } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonSocial'; import type { IAppLoadCommonVisualSettings } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonVisualSettings'; import type { IAppLoadCommonEvents } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonEvents'; import type { IAppLoadCommonBanner } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonBanner'; import type { ICategory } from '@/interfaces/basklee/category/ICategory'; import type { IAppLoadProduct, IProductSeller, } from '@/interfaces/basklee/products/IProduct'; import type { IAppLoadCommonTariff } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonTariff'; import type { IAppLoadCommonWalletValue } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonWalletValue'; import type { IAppLoadCommonVariables } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonVariables'; import type { IAppLoadCommonContact } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonContact'; export interface IAppLoadCommon { // Idiomas disponibles y su moneda y sus unidades predeterminadas. locale: Record<string, IAppLoadCommonLocale>; // Monedas, reglas de formato, valores de conversión y disponibilidad en el // selector. currencies: Record<string, IAppLoadCommonCurrency>; // Unidades de peso y factores de conversión. weights: Record<string, IAppLoadCommonUnit>; // Unidades de longitud y factores de conversión. lengths: Record<string, IAppLoadCommonUnit>; // Si hay un plugin de geocodificación elegido para buscar direcciones por // coordenadas. Las sugerencias de texto de dirección y ciudad dependen del // país. geo_location_enabled: boolean; /** ISO codes of the shop's shipping countries, sorted. */ shipping_countries?: string[]; // Si la sesión actual pertenece a un cliente que ha iniciado sesión. is_authenticated: boolean; // Saldo del cliente por moneda, cuando hay un monedero disponible. wallet?: Record<string, IAppLoadCommonWalletValue>; // Tamaños de logotipo y favicon. logos: IAppLoadCommonLogos; // Claves públicas para integraciones externas, incluida la clave de la API de // Yandex Maps. public_keys: Record<string, string>; // Coordenadas del centro del mapa predeterminadas configuradas para la tienda. default_map: IGeoCoordinates; // Metadatos de la página de inicio de la tienda seo?: IAppLoadCommonSeo[]; // Enlaces a redes sociales. sm?: IAppLoadCommonSocial[]; // Contadores iniciales del carrito y de favoritos y valores predeterminados de // funciones. variables?: IAppLoadCommonVariables; // Nombre de la empresa, datos de contacto e información legal. contact?: IAppLoadCommonContact; // Opciones de visualización de los menús, las listas y los elementos de la // tienda. visual_settings?: IAppLoadCommonVisualSettings; // Eventos y mensajes que se muestran en la tienda. events?: IAppLoadCommonEvents[]; // Colecciones de banners de la página de inicio. main_banner?: Record<string, IAppLoadCommonBanner[]>; // Árbol de categorías para la navegación de la tienda. catalog?: ICategory[]; // Productos iniciales de la tienda. Cada entrada contiene `seller_id`; lee el // vendedor completo en `sellers`. products?: IAppLoadProduct[]; // Productos personalizados según búsquedas y categorías anteriores. Cada // entrada contiene `seller_id`; lee el vendedor completo en `sellers`. Vacío // para los invitados. featured?: IAppLoadProduct[]; // Datos de los vendedores indexados por ID de vendedor. Los stores de // productos usan este objeto para dar `IProduct.seller` a los componentes. sellers: Record<string, IProductSeller>; // Sugerencias localizadas para el campo de búsqueda. search_hints?: Record<string, string>[]; // Planes que vende esta tienda, con sus precios y opciones, como en // `subscriptions_guest_search`. Una tienda sin lista de planes recibe una // lista `data` vacía. tariffs?: IAppLoadCommonTariff; }app/app.vueEl componente raíz aplica el tema seleccionado con
BaskleeThemeProvidery muestra la página de la ruta actual conNuxtPagedentro deNuxtLayout.NuxtLoadingIndicatordibuja una barra fina en la parte superior de la ventana con el color del texto de la cabecera, para que se vea sobre la barra oscura de la cabecera, y con el color de peligro tras un error. Se ejecuta durante la navegación entre páginas y mientras hay una solicitud de la tienda en curso: guardar, actualizar, cargar e iniciar sesión. Los botones siguen desactivados y los lectores de pantalla reciben el texto de estado; la página no muestra una franja de estado aparte.Así se conectan las páginas de ruta, los diseños y el middleware de ruta global con el ciclo de vida de la aplicación.
Código fuente
<script setup lang="ts"> import { watch } from 'vue'; import { useBaskleeStore } from '@/stores/basklee'; import { NuxtLayout, NuxtLoadingIndicator, NuxtPage } from '#components'; import { showError, useHead, useRoute } from '#imports'; import BaskleeThemeProvider from '@/components/basklee/theme/BaskleeThemeProvider.vue'; import { useBaskleeTheme } from '@/composables/useBaskleeTheme'; import { storefrontPageError } from '@/composables/useBaskleeMissingPage'; import { storefrontIconLinks } from '@/utils/basklee/pageSeo'; const store = useBaskleeStore(); const route = useRoute(); const { mode } = useBaskleeTheme(); // The store's icon from the admin panel (logos.ico) for browser tabs and // search results; a page without it keeps the browser default. useHead(() => ({ htmlAttrs: { lang: store.localeCode }, link: storefrontIconLinks(store.init?.logos?.ico), })); // The middleware opens the 503 error page during navigation. A refresh that // fails while a page is open, for example after sign-in, opens it too. watch( () => store.status, (status) => { const error = route.matched.length ? storefrontPageError(status, false, '') : undefined; if (error) { void showError(error); } }, ); </script> <template> <BaskleeThemeProvider :mode="mode" class="min-h-screen" > <NuxtLoadingIndicator :height="2" color="var(--basklee-inverse-text)" error-color="var(--basklee-danger)" /> <NuxtLayout> <NuxtPage /> </NuxtLayout> </BaskleeThemeProvider> </template>app/pages/index.vueLa página de inicio de la plantilla lee el estado de carga del store. El middleware hace la primera solicitud antes de que se abra la página.
Mientras Application Load está pendiente, la página muestra un mensaje de carga. Un Application Load fallido nunca llega a la página: el middleware abre en su lugar la página de error de la tienda.
Si todo va bien, muestra
StorefrontHome: banners, categorías, eventos y selecciones de productos de Application Load, más los productos nuevos pedidos conproducts_search. Si los productos nuevos no se cargan, la página muestra un mensaje con su propio botón Reintentar. Los metadatos de la página vienen destore.init.seo. Más en la sección Hallazgos destacados abre la página/featured.Código fuente
<script setup lang="ts"> import { useBaskleePageSeo } from '@/composables/useBaskleePageSeo'; import { computed, defineAsyncComponent, onMounted, ref } from 'vue'; import { useHead, navigateTo, useRoute } from '#imports'; import { useBaskleeStore } from '@/stores/basklee'; import { useBaskleeHomeProducts } from '@/composables/useBaskleeHomeProducts'; import { useBaskleeStorefront } from '@/composables/useBaskleeStorefront'; import { useBaskleeSignIn } from '@/composables/useBaskleeSignIn'; import { eventReturnPath } from '@/utils/basklee/signInReturn'; import StorefrontHome from '@/components/basklee/storefront/StorefrontHome.vue'; import { homeLabels } from '@/utils/basklee/homeLabels'; import { headerLabels } from '@/utils/basklee/headerLabels'; import { getStorefrontSeo } from '@/utils/basklee/seo'; import type { IAppLoadCommonBanner } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonBanner'; import type { IAppLoadCommonEvents } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonEvents'; const EventEnrollmentDialog = defineAsyncComponent( () => import('@/components/basklee/events/EventEnrollmentDialog.vue'), ); const enrollment = ref<IAppLoadCommonEvents>(); function openEnrollment(event: IAppLoadCommonEvents) { if (event.promo) { enrollment.value = event; } } // A guest's click opens sign-in at once; it returns with `?event=<id>`. function selectEvent(event: IAppLoadCommonEvents) { if (event.promo && !store.isAuthenticated) { signIn.requireSignIn(eventReturnPath(route.fullPath, event.id)); return; } openEnrollment(event); } // The return address `?event=<id>` opens the dialog again for that event, // without navigating anywhere. Closing it removes the parameter. function reopenEnrollment() { const id = Number(route.query.event); const event = store.init?.events?.find((item) => item.id === id); if (event) { openEnrollment(event); } } function closeEnrollment() { enrollment.value = undefined; if (route.query.event === undefined) { return; } const query = { ...route.query }; delete query.event; return navigateTo({ path: route.path, query }, { replace: true }); } function openBannerCategory(banner: IAppLoadCommonBanner) { if (banner.category != null) { return navigateTo({ path: `/category/${banner.category}`, query: { locale: store.localeCode }, }); } } const store = useBaskleeStore(); const route = useRoute(); const signIn = useBaskleeSignIn(); const { actions, variants, selection: headerSelection, } = useBaskleeStorefront(); const homeProducts = useBaskleeHomeProducts(); const labels = computed(() => headerLabels(store.localeCode)); const homeCopy = computed(() => homeLabels(store.localeCode)); const metadata = computed(() => getStorefrontSeo(store.init?.seo ?? [], store.localeCode), ); function namedMeta(name: string) { return metadata.value.meta.findLast( (tag) => 'name' in tag && tag.name === name, )?.content; } onMounted(reopenEnrollment); useBaskleePageSeo('home', () => store.localeCode, { title: () => metadata.value.title || store.init?.contact?.company_name || 'Basklee', description: () => namedMeta('description'), keywords: () => namedMeta('keywords'), }); useHead(() => ({ meta: metadata.value.meta.filter( (tag) => !('name' in tag && ['description', 'keywords'].includes(tag.name)), ), })); </script> <template> <main> <h1 class="sr-only"> {{ store.init?.contact?.company_name || 'Basklee' }} </h1> <p v-if="homeProducts.error.value" role="status" class=" flex flex-wrap items-center gap-3 mx-auto max-w-[1440px] px-4 sm:px-6 lg:px-8 text-sm text-basklee-muted " > {{ homeCopy.newFailed }} <button type="button" class=" inline-flex h-11 items-center justify-center px-6 text-xs font-medium uppercase tracking-[0.08em] rounded-none border border-solid border-basklee-text bg-transparent text-basklee-text cursor-pointer outline-none hover:bg-basklee-hover focus-visible:bg-basklee-hover " @click="homeProducts.load()" > {{ homeCopy.retry }} </button> </p> <StorefrontHome v-if="store.status === 'success'" :product-actions-disabled=" actions.pending.value || actions.needsRefresh.value " @add="actions.run('add', $event)" @remove="actions.run('remove', $event)" @toggle-favorite="actions.run('toggleFavorite', $event)" @subscribe="actions.run('subscribe', $event)" @unsubscribe="actions.run('unsubscribe', $event)" @preorder="actions.openPreorder" @select-variant="variants.select" @request-secondary-variants="variants.requestSecondary" @select-category=" navigateTo({ path: `/category/${$event.id}`, query: { locale: store.localeCode }, }) " @select-product=" navigateTo({ path: `/product/${$event.id}`, query: { locale: store.localeCode }, }) " @select-seller=" navigateTo({ path: '/sellers', query: { seller: $event.id, locale: store.localeCode }, }) " @select-banner="openBannerCategory" @select-featured=" navigateTo({ path: '/featured', query: { locale: store.localeCode } }) " @select-event="selectEvent" /> <div v-else class=" grid justify-items-start gap-4 mx-auto max-w-[1440px] px-4 py-12 sm:px-6 lg:px-8 text-sm " :aria-busy="store.status === 'pending'" > <p class="m-0" role="status" > {{ homeCopy.loading }} </p> </div> <EventEnrollmentDialog v-if="enrollment" :key="enrollment.id" :event="enrollment" @close="closeEnrollment" /> </main> </template>
Cada solicitud SSR tiene su propia instancia de Pinia.
El navegador recibe ese estado durante la hidratación. Tras iniciar o cerrar sesión, llama a reset y refresh para sustituir el perfil y los métodos disponibles.