@techsio/storefront-data
Version:
Medusa-first storefront data layer built on TanStack Query.
89 lines (88 loc) • 3.28 kB
JavaScript
const isPlainObject = (value)=>{
if (!value || "object" != typeof value) return false;
const proto = Object.getPrototypeOf(value);
return proto === Object.prototype || null === proto;
};
const normalizeNamespace = (namespace)=>{
if ("string" == typeof namespace) return [
namespace
];
return namespace;
};
const walkValue = (value, visited, options)=>{
if (Array.isArray(value)) {
if (visited.has(value)) throw new Error("QueryKey contains a circular reference");
visited.add(value);
const result = value.map((entry)=>walkValue(entry, visited, options)).filter((entry)=>!options?.stripUndefined || void 0 !== entry);
visited.delete(value);
return result;
}
if (isPlainObject(value)) {
if (visited.has(value)) throw new Error("QueryKey contains a circular reference");
visited.add(value);
const entries = Object.entries(value).sort(([a], [b])=>a.localeCompare(b));
const result = {};
for (const [key, entryValue] of entries){
if (options?.omitKeys?.has(key)) continue;
const normalizedEntry = walkValue(entryValue, visited, options);
if (!options?.stripUndefined || void 0 !== normalizedEntry) result[key] = normalizedEntry;
}
visited.delete(value);
return result;
}
return value;
};
function normalizeQueryKeyParams(params, options) {
if (!isPlainObject(params)) throw new Error("QueryKey params must be a plain object. Use a serializer before normalizeQueryKeyParams.");
const visited = new WeakSet();
const omitKeys = new Set(options?.omitKeys ?? []);
const normalized = walkValue(params, visited, {
omitKeys,
stripUndefined: true
});
if (isPlainObject(normalized)) return normalized;
return {};
}
function normalizeQueryKeyPart(value, options) {
if (void 0 === value) return {};
if (isPlainObject(value)) return normalizeQueryKeyParams(value, options);
return walkValue(value, new WeakSet());
}
function createQueryKey(namespace, ...parts) {
const scope = normalizeNamespace(namespace);
const visited = new WeakSet();
return [
...scope,
...parts.map((part)=>walkValue(part, visited))
];
}
function appendQueryKey(base, ...parts) {
const visited = new WeakSet();
return [
...base,
...parts.map((part)=>walkValue(part, visited))
];
}
function createDomainQueryKeys(namespace, domain) {
return {
all: ()=>createQueryKey(namespace, domain),
list: (params)=>createQueryKey(namespace, domain, "list", normalizeQueryKeyPart(params, {
omitKeys: [
"enabled"
]
})),
detail: (params)=>createQueryKey(namespace, domain, "detail", normalizeQueryKeyPart(params, {
omitKeys: [
"enabled"
]
}))
};
}
function createQueryKeyFactory(namespace) {
const scope = normalizeNamespace(namespace);
return {
scope,
key: (...parts)=>createQueryKey(scope, ...parts)
};
}
export { appendQueryKey, createDomainQueryKeys, createQueryKey, createQueryKeyFactory, normalizeQueryKeyParams, normalizeQueryKeyPart };