Template
Call hydrogen's storefront.graphql directly, drop the compat shim
Completes the migration started in f8c3ef9. That commit put hydrogen
underneath the existing shopifyFetch wrapper; this one removes the
wrapper so every query uses the package's own client API.
- All 22 call sites now call storefront.graphql(DOCUMENT, { variables })
(cachedStorefront for shop policies) instead of shopifyFetch, which
emulated the old client's {query, variables} -> {data} shape.
- shopifyFetch is replaced by unwrapStorefrontResult(result, operation),
which is only an error policy, not a transport wrapper: it returns
data and throws when Shopify reports GraphQL errors, since hydrogen
returns those rather than throwing. Naming the operation means a
failure points at the call site instead of just at "Shopify".
- Environment reads move to services/shopify/config, so client.ts is
only the hydrogen clients and shop-pay-button no longer imports from
a query module just to get the store domain.
- Removes @shopify/storefront-api-client, the superseded client. It had
no importers.
The SHOPIFY_STOREFRONT_API_URL export is gone too — hydrogen builds the
endpoint from storeDomain and apiVersion, and nothing else used it.
No behaviour change intended: same documents, same env var names, same
2025-07 API pin, same caching split between the two clients.
yarn typecheck passes with 0 errors. Verified against mock.shop: build
prerenders the policy pages, and in the browser product grid, search,
collection filters, cart restore, quantity update and discount-code
apply all work with no console errors. Customer account flows remain
untested — they need real credentials.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JaxgqPbFxLsSuLPZom2kdC
This commit is contained in:
co-authored by
Claude Opus 5
parent
f8c3ef9e0e
commit
fe78293312
+34
-59
@@ -1,23 +1,20 @@
|
||||
// Shopify Storefront API access, backed by `@shopify/hydrogen` (preview build).
|
||||
// Storefront API clients, built on `@shopify/hydrogen`.
|
||||
//
|
||||
// The package supplies the transport (`createStorefrontClient`) and the typed
|
||||
// query documents (`gql`, see graphql/*.ts). `shopifyFetch` keeps the call
|
||||
// shape the rest of the app already uses — `{ query, variables }` in, `{ data }`
|
||||
// out, throwing on GraphQL errors — but now infers `data` from the document.
|
||||
// Call sites use the package's own API — `storefront.graphql(DOCUMENT, {
|
||||
// variables })` — and pass the result through `unwrapStorefrontResult`, which
|
||||
// applies this app's error policy: fail loudly. Hydrogen deliberately does not
|
||||
// do that itself, because a 200 carrying partial data and GraphQL errors is a
|
||||
// valid response that some callers want to render.
|
||||
import {
|
||||
createShopifyRequestContext,
|
||||
createStorefrontClient,
|
||||
StorefrontApiError,
|
||||
type AnyStorefrontQueryString,
|
||||
type StorefrontApi,
|
||||
type GraphQLFormattedError,
|
||||
} from '@shopify/hydrogen';
|
||||
|
||||
const SHOPIFY_STORE_DOMAIN = process.env.NEXT_PUBLIC_SHOPIFY_DOMAIN;
|
||||
const SHOPIFY_STOREFRONT_ACCESS_TOKEN =
|
||||
process.env.NEXT_PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN;
|
||||
const SHOPIFY_API_VERSION =
|
||||
process.env.NEXT_PUBLIC_SHOPIFY_API_VERSION || '2025-07';
|
||||
const SHOPIFY_STOREFRONT_API_URL = `https://${SHOPIFY_STORE_DOMAIN}/api/${SHOPIFY_API_VERSION}/graphql.json`;
|
||||
import {
|
||||
SHOPIFY_API_VERSION,
|
||||
SHOPIFY_STORE_DOMAIN,
|
||||
SHOPIFY_STOREFRONT_ACCESS_TOKEN,
|
||||
} from '@/services/shopify/config';
|
||||
|
||||
// No incoming request and no buyer context: these clients are module-scoped and
|
||||
// serve both server rendering and the browser-side hooks, so they must not close
|
||||
@@ -36,7 +33,6 @@ const fetchWith = (overrides: RequestInit): typeof globalThis.fetch =>
|
||||
const config = {
|
||||
storeDomain: SHOPIFY_STORE_DOMAIN!,
|
||||
apiVersion: SHOPIFY_API_VERSION,
|
||||
// `mock.shop` and other tokenless storefronts leave this unset.
|
||||
publicStorefrontToken: SHOPIFY_STOREFRONT_ACCESS_TOKEN,
|
||||
};
|
||||
|
||||
@@ -51,8 +47,8 @@ export const storefront = createStorefrontClient({
|
||||
});
|
||||
|
||||
/**
|
||||
* Client for catalogue data that changes rarely (shop policies, and anything
|
||||
* else safe to serve from Next's data cache for an hour).
|
||||
* Client for data that changes rarely (shop policies, and anything else safe to
|
||||
* serve from Next's data cache for an hour).
|
||||
*/
|
||||
export const cachedStorefront = createStorefrontClient({
|
||||
type: 'public',
|
||||
@@ -60,49 +56,28 @@ export const cachedStorefront = createStorefrontClient({
|
||||
config: { ...config, fetch: fetchWith({ next: { revalidate: 3600 } }) },
|
||||
});
|
||||
|
||||
interface ShopifyFetchArgs<TDoc extends AnyStorefrontQueryString> {
|
||||
query: TDoc;
|
||||
variables?: StorefrontApi.VariablesOf<TDoc>;
|
||||
/** Serve from Next's data cache instead of hitting Shopify every time. */
|
||||
cache?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a `gql()` document and returns its data.
|
||||
* Returns the data from a `graphql()` result, throwing if Shopify reported any
|
||||
* GraphQL errors. Transport failures — non-200, timeouts, unparseable bodies —
|
||||
* have already thrown as `StorefrontApiError` by this point.
|
||||
*
|
||||
* Hydrogen returns GraphQL errors rather than throwing them (a 200 with partial
|
||||
* data is still a valid response), so this re-raises them to preserve the
|
||||
* fail-loudly behaviour the callers were written against. Transport failures
|
||||
* already throw as `StorefrontApiError`.
|
||||
* `operation` names the query in the log and the thrown message, so a failure
|
||||
* points at the call site rather than just at "Shopify".
|
||||
*/
|
||||
export async function shopifyFetch<TDoc extends AnyStorefrontQueryString>({
|
||||
query,
|
||||
variables,
|
||||
cache = false,
|
||||
}: ShopifyFetchArgs<TDoc>): Promise<{
|
||||
data: StorefrontApi.ResultOf<TDoc>;
|
||||
}> {
|
||||
const client = cache ? cachedStorefront : storefront;
|
||||
|
||||
try {
|
||||
const { data, errors } = await client.graphql(query, {
|
||||
variables,
|
||||
} as never);
|
||||
|
||||
if (errors?.length) {
|
||||
console.error('Shopify API errors:', errors);
|
||||
throw new Error(`Shopify GraphQL errors: ${JSON.stringify(errors)}`);
|
||||
}
|
||||
|
||||
return { data: data as StorefrontApi.ResultOf<TDoc> };
|
||||
} catch (error) {
|
||||
if (error instanceof StorefrontApiError) {
|
||||
console.error('Shopify fetch error:', error.toJSON());
|
||||
} else {
|
||||
console.error('Shopify fetch error:', error);
|
||||
}
|
||||
throw error;
|
||||
export function unwrapStorefrontResult<TData>(
|
||||
result: { data: TData | null; errors?: GraphQLFormattedError[] },
|
||||
operation: string
|
||||
): TData {
|
||||
if (result.errors?.length) {
|
||||
console.error(`Shopify GraphQL errors (${operation}):`, result.errors);
|
||||
throw new Error(
|
||||
`Shopify GraphQL errors (${operation}): ${JSON.stringify(result.errors)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export { SHOPIFY_STORE_DOMAIN, SHOPIFY_STOREFRONT_API_URL };
|
||||
if (result.data == null) {
|
||||
throw new Error(`Shopify returned no data for ${operation}.`);
|
||||
}
|
||||
|
||||
return result.data;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user