@scayle/storefront-nuxt
Version:
Nuxt integration for the SCAYLE Commerce Engine and Storefront API
68 lines (67 loc) • 2.59 kB
JavaScript
import { unwrap, DEFAULT_RPC_HTTP_METHOD } from "@scayle/storefront-core";
import { useAsyncData, useRuntimeConfig, useNuxtApp } from "nuxt/app";
import { useCoreLog } from "../useCoreLog.js";
import { useCurrentShop } from "./useCurrentShop.js";
import { toValue, isRef } from "vue";
import { rpcHttpMethods as rpcHttpMethodManifest } from "#virtual/rpcHttpMethods";
function getFetch(nuxtApp, log) {
const fetch = nuxtApp.ssrContext?.event.context.$fetchWithContext ?? $fetch;
if (nuxtApp.ssrContext?.event && !nuxtApp.ssrContext?.event.context.$fetchWithContext) {
log.error("event.$fetchWithContext was not found!");
}
return fetch;
}
export const defaultCachedData = (key, nuxtApp) => {
const hydrationData = nuxtApp.isHydrating ? nuxtApp.payload.data[key] : nuxtApp.static.data[key];
return hydrationData ?? nuxtApp._asyncData[key]?.data.value;
};
export function useRpc(method, key, params, options) {
const currentShop = useCurrentShop();
const log = useCoreLog("rpc");
const nuxtApp = useNuxtApp();
const {
public: { storefront }
} = useRuntimeConfig();
options ??= {};
options.lazy ??= storefront.rpcDefaultLazy;
const asyncData = useAsyncData(
key,
async () => {
const apiBasePath = currentShop.value?.apiBasePath ?? "/api";
const fetch = getFetch(nuxtApp, log);
const httpMethod = rpcHttpMethodManifest[method] ?? DEFAULT_RPC_HTTP_METHOD;
const resolvedParams = toValue(params);
const headers = {
"x-shop-id": `${currentShop.value?.shopId}`
};
const path = `/rpc/${method}`;
let fetchOptions;
if (httpMethod === "GET") {
fetchOptions = {
method: httpMethod,
baseURL: apiBasePath,
headers,
params: resolvedParams !== void 0 && resolvedParams !== null ? { payload: JSON.stringify(resolvedParams) } : void 0
};
} else {
fetchOptions = {
method: httpMethod,
body: { payload: resolvedParams },
baseURL: apiBasePath,
headers
};
}
return await unwrap(
await fetch(path, fetchOptions)
);
},
{
// TODO v9: Remove automatically watching params with next major and solely rely on passed watch options and reactive keys
// Both refs and getter functions are valid watch sources
...isRef(params) || typeof params === "function" ? { watch: [params] } : {},
getCachedData: storefront.legacy?.enableDefaultGetCachedDataOverride ? defaultCachedData : void 0,
...options
}
);
return asyncData;
}