Last active
August 17, 2023 02:13
-
-
Save DennisKraaijeveld/17c63313c6092d5c014e7312f6d8a138 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Check if the collection has subcollections. We will only query for the metafield subcollection here. | |
const {collection: metaSubcollection} = await context.storefront.query( | |
METAFIELD_CHECK_QUERY, | |
{ | |
variables: { | |
handle: collectionHandle, | |
}, | |
}, | |
); | |
const subCollectionIds = | |
metaSubcollection && | |
(metaSubcollection.metafields as any[]).length > 0 && | |
metaSubcollection.metafields[0]?.value | |
? JSON.parse(metaSubcollection.metafields[0].value) | |
: null; | |
let subCollectionHandles = []; | |
if ( | |
subCollectionIds && | |
subCollectionIds != null && | |
(subCollectionIds as any[]).length > 0 | |
) { | |
const idsArray = Array.isArray(subCollectionIds) | |
? subCollectionIds | |
: [subCollectionIds]; | |
// Get the handles of the subcollections. We will use this to check if the childCollectionHandle is a valid handle. | |
const handleResponses = await Promise.all( | |
idsArray.map((id) => | |
context.storefront.query(CHILDCOLLECTIONHANDLE_CHECK_QUERY, { | |
variables: { | |
id: id as string, | |
}, | |
}), | |
), | |
); | |
subCollectionHandles = handleResponses | |
.map((response) => | |
response.collection ? response.collection.handle : null, | |
) | |
.filter(Boolean); | |
// Check if on childCollectionRoute | |
if ( | |
childCollectionHandle && | |
!subCollectionHandles.includes(childCollectionHandle) | |
) { | |
throw new Response('collection', {status: 404}); | |
} | |
} else if (childCollectionHandle) { | |
throw new Response('collection', {status: 404}); | |
} | |
const {collection, collections} = await context.storefront.query<{ | |
collection: CollectionType; | |
collections: CollectionConnection; | |
}>(COLLECTION_QUERY, { | |
variables: { | |
...paginationVariables, | |
handle: childCollectionHandle ?? collectionHandle, | |
filters, | |
sortKey, | |
reverse, | |
country, | |
language, | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment