61 lines
1.7 KiB
TypeScript
61 lines
1.7 KiB
TypeScript
import {CacheShort} from '@shopify/hydrogen';
|
|
import type {SanityContext} from 'hydrogen-sanity';
|
|
|
|
/**
|
|
* Manual/display rating + count pulled from Sanity product documents.
|
|
* If unset, the UI should hide the rating line entirely.
|
|
*
|
|
* Source fields: `product.abiirPdp.rating` + `product.abiirPdp.reviewCount`
|
|
*/
|
|
const DISPLAY_RATINGS_GROQ = /* groq */ `*[_type == "product" && store.slug.current in $handles]{
|
|
"h": store.slug.current,
|
|
"rating": abiirPdp.rating,
|
|
"reviewCount": abiirPdp.reviewCount
|
|
}`;
|
|
|
|
type Row = {
|
|
h?: string | null;
|
|
rating?: number | null;
|
|
reviewCount?: number | null;
|
|
};
|
|
|
|
export type DisplayRating = {rating: number; reviewCount: number};
|
|
|
|
export async function loadProductDisplayRatingsByHandles(args: {
|
|
sanity: SanityContext;
|
|
handles: string[];
|
|
}): Promise<Record<string, DisplayRating>> {
|
|
const unique = [...new Set(args.handles.map((h) => h.trim()).filter(Boolean))];
|
|
if (unique.length === 0) return {};
|
|
|
|
const raw = await args.sanity
|
|
.fetch<Row[] | null>(
|
|
DISPLAY_RATINGS_GROQ,
|
|
{handles: unique},
|
|
{hydrogen: {cache: CacheShort()}},
|
|
)
|
|
.catch((): null => null);
|
|
|
|
const data = Array.isArray(raw) ? raw : [];
|
|
const out: Record<string, DisplayRating> = {};
|
|
for (const r of data) {
|
|
const h = r.h?.trim();
|
|
if (!h) continue;
|
|
const rating = typeof r.rating === 'number' ? r.rating : null;
|
|
const reviewCount = typeof r.reviewCount === 'number' ? r.reviewCount : null;
|
|
if (
|
|
rating == null ||
|
|
reviewCount == null ||
|
|
!Number.isFinite(rating) ||
|
|
!Number.isFinite(reviewCount) ||
|
|
rating <= 0 ||
|
|
reviewCount <= 0
|
|
) {
|
|
continue;
|
|
}
|
|
out[h] = {rating, reviewCount};
|
|
}
|
|
return out;
|
|
}
|
|
|