From 53644323317081d7e712a0ddd75a9a14f2f4efa3 Mon Sep 17 00:00:00 2001 From: Anthony Frehner Date: Tue, 29 Nov 2022 16:02:32 -0700 Subject: [PATCH] return type working, props not --- .../app/routes/api/server-event.tsx | 49 ++++++++++++++++--- 1 file changed, 42 insertions(+), 7 deletions(-) diff --git a/templates/demo-store/app/routes/api/server-event.tsx b/templates/demo-store/app/routes/api/server-event.tsx index 915ebf38db..9517264832 100644 --- a/templates/demo-store/app/routes/api/server-event.tsx +++ b/templates/demo-store/app/routes/api/server-event.tsx @@ -1,6 +1,7 @@ import {type LoaderArgs, json} from '@shopify/hydrogen-remix'; import {flattenConnection} from '@shopify/hydrogen-react'; import { + Collection, Product, ProductConnection, ProductVariant, @@ -11,6 +12,27 @@ import invariant from 'tiny-invariant'; export async function loader({request, context: {storefront}}: LoaderArgs) { const url = new URL(request.url); + const data = await getAnalyticDataByPageType({ + pageType: 'product', + payload: {} as Product, + storefront, + queries: {} as AnalyticsQueries, + }); + + const data2 = await getAnalyticDataByPageType({ + pageType: 'collection', + payload: {} as Collection, + storefront, + queries: {} as AnalyticsQueries, + }); + + const data3 = await getAnalyticDataByPageType({ + pageType: 'home', + payload: null, + storefront, + queries: {} as AnalyticsQueries, + }); + return json({ ga: ['event', 'page_view'], }); @@ -27,24 +49,36 @@ type ProductPayload = { [key: string]: unknown; }; +type PageToPayloadMap = { + product: Product; + collection: Collection; + home: null; +}; + +type ReturnType = PageToPayloadMap[T]; + // Function supplied by Hydrogen (hydrogen-remix or maybe even hydrogen-react) -async function getAnalyticDataByPageType({ +async function getAnalyticDataByPageType({ pageType, payload, storefront, queries, }: { - pageType: string; - payload: unknown; + pageType: T; + payload: PageToPayloadMap[T]; storefront: LoaderArgs['context']['storefront']; queries: AnalyticsQueries; -}) { +}): Promise> { // Default cache time for analytics queries const cache = storefront.CacheLong(); if (pageType === 'product') { // Do checks for required payload vars - const {handle, selectedOptions} = payload as ProductPayload; + + // unfortunately, TS itself seems limited in being able to infer this, so we have to cast it ourselves - instead of being able to do the following: + // const {handle, selectedOptions} = payload; + const {handle, selectedOptions} = payload as Product; + const data = await storefront.query<{ product: Product & {selectedVariant?: ProductVariant}; }>(queries[pageType], { @@ -55,9 +89,10 @@ async function getAnalyticDataByPageType({ cache, }); // Propagate data.errors check - return data.product; + // 'as any' is required for TS to work here, it seems. It's a limitation of TS itself + return data.product as any; } - return {}; + return {} as any; } // Queries supplied by developer