133 lines
4.1 KiB
TypeScript
133 lines
4.1 KiB
TypeScript
import {CacheNone, CacheShort} from '@shopify/hydrogen';
|
|
import type {SanityContext} from 'hydrogen-sanity';
|
|
import {unwrapSanityQueryResult} from '~/lib/abiirProductDetail';
|
|
import type {PdpProductReview, PdpProductReviewStats} from '~/lib/productReviewTypes';
|
|
|
|
const REVIEWS_CAP = 50;
|
|
|
|
const PRODUCT_REVIEWS_GROQ = /* groq */ `*[
|
|
_type == "productReview"
|
|
&& isVisible == true
|
|
&& (
|
|
productHandle == $handle
|
|
|| product->store.slug.current == $handle
|
|
)
|
|
] | order(submittedAt desc) [0...${REVIEWS_CAP}] {
|
|
rating,
|
|
title,
|
|
body,
|
|
authorDisplayName,
|
|
submittedAt
|
|
}`;
|
|
|
|
export function computeProductReviewStats(
|
|
reviews: PdpProductReview[],
|
|
): PdpProductReviewStats | null {
|
|
if (!reviews.length) return null;
|
|
const sum = reviews.reduce((s, r) => s + (typeof r.rating === 'number' ? r.rating : 0), 0);
|
|
const count = reviews.length;
|
|
const averageRating = Math.round((sum / count) * 10) / 10;
|
|
return {averageRating, count};
|
|
}
|
|
|
|
/**
|
|
* Public storefront reviews (visible only) for a Shopify product handle.
|
|
*/
|
|
export async function loadProductReviewsForHandle(args: {
|
|
sanity: SanityContext;
|
|
handle: string;
|
|
}): Promise<{reviews: PdpProductReview[]; stats: PdpProductReviewStats | null}> {
|
|
// UGC: avoid Hydrogen CacheLong (empty list was cached) and Sanity CDN lag after creates.
|
|
const raw = await args.sanity
|
|
.fetch<PdpProductReview[] | null>(PRODUCT_REVIEWS_GROQ, {handle: args.handle}, {
|
|
useCdn: false,
|
|
hydrogen: {cache: CacheNone()},
|
|
})
|
|
.catch((): null => null);
|
|
const data = unwrapSanityQueryResult<PdpProductReview[] | null>(raw);
|
|
const list = Array.isArray(data) ? data : [];
|
|
const reviews = list.map((r) => ({
|
|
...r,
|
|
body: String(r.body ?? '').trim(),
|
|
authorDisplayName: String(r.authorDisplayName ?? 'Customer').trim() || 'Customer',
|
|
title: r.title ? String(r.title).trim() : null,
|
|
}));
|
|
return {
|
|
reviews,
|
|
stats: computeProductReviewStats(reviews),
|
|
};
|
|
}
|
|
|
|
const DUPLICATE_CHECK_GROQ = /* groq */ `*[
|
|
_type == "productReview"
|
|
&& source == "customer"
|
|
&& productHandle == $handle
|
|
&& shopifyCustomerId == $shopifyCustomerId
|
|
][0]{ _id }`;
|
|
|
|
/**
|
|
* Dedupe before create: use the **write** client so results are not CDN-stale.
|
|
*/
|
|
export async function findExistingProductReviewId(
|
|
client: import('@sanity/client').SanityClient,
|
|
args: {productHandle: string; shopifyCustomerId: string},
|
|
): Promise<string | null> {
|
|
const data = await client
|
|
.fetch<{_id: string} | null>(DUPLICATE_CHECK_GROQ, {
|
|
handle: args.productHandle,
|
|
shopifyCustomerId: args.shopifyCustomerId,
|
|
})
|
|
.catch((): null => null);
|
|
return data?._id ?? null;
|
|
}
|
|
|
|
const BATCH_REVIEW_STATS_GROQ = /* groq */ `*[_type == "productReview" && isVisible == true]{
|
|
"h": coalesce(productHandle, product->store.slug.current),
|
|
"r": rating
|
|
}[h in $handles]`;
|
|
|
|
type BatchReviewRow = {h: string; r: number | null};
|
|
|
|
/**
|
|
* Average rating + count per Shopify product `handle` (visible UGC in Sanity).
|
|
* For PLP/search batching; short cache only — not CacheLong.
|
|
*/
|
|
export async function loadProductReviewStatsByHandles(args: {
|
|
sanity: SanityContext;
|
|
handles: string[];
|
|
}): Promise<Record<string, PdpProductReviewStats>> {
|
|
const unique = [
|
|
...new Set(args.handles.map((h) => h.trim()).filter(Boolean)),
|
|
] as string[];
|
|
if (unique.length === 0) return {};
|
|
|
|
const raw = await args.sanity
|
|
.fetch<BatchReviewRow[] | null>(BATCH_REVIEW_STATS_GROQ, {handles: unique}, {
|
|
useCdn: false,
|
|
hydrogen: {cache: CacheShort()},
|
|
})
|
|
.catch((): null => null);
|
|
|
|
const data = Array.isArray(raw) ? raw : [];
|
|
const agg = new Map<string, {sum: number; count: number}>();
|
|
for (const row of data) {
|
|
const h = row.h?.trim();
|
|
if (!h) continue;
|
|
const n = typeof row.r === 'number' && Number.isFinite(row.r) ? row.r : 0;
|
|
const cur = agg.get(h) ?? {sum: 0, count: 0};
|
|
cur.sum += n;
|
|
cur.count += 1;
|
|
agg.set(h, cur);
|
|
}
|
|
|
|
const out: Record<string, PdpProductReviewStats> = {};
|
|
for (const [h, {sum, count}] of agg) {
|
|
if (count < 1) continue;
|
|
out[h] = {
|
|
averageRating: Math.round((sum / count) * 10) / 10,
|
|
count,
|
|
};
|
|
}
|
|
return out;
|
|
}
|