Skip to content

Commit

Permalink
Update WeaverseClient fetchWithCache method
Browse files Browse the repository at this point in the history
  • Loading branch information
hta218 committed Jul 7, 2024
1 parent 4d7b5e4 commit e0bc85a
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions packages/hydrogen/src/weaverse-client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { createWithCache, generateCacheControlHeader } from '@shopify/hydrogen'

import type {
AllCacheOptions,
FetchProjectPayload,
Expand Down Expand Up @@ -71,7 +70,10 @@ export class WeaverseClient {
}
}

fetchWithCache = <T>(url: string, options: FetchWithCacheOptions = {}) => {
fetchWithCache = async <T>(
url: string,
options: FetchWithCacheOptions = {},
) => {
let cacheKey = [url, options.body]
let {
strategy = this.storefront.CacheCustom({
Expand All @@ -81,22 +83,27 @@ export class WeaverseClient {
}),
...reqInit
} = options
if (this.configs.isDesignMode) {
try {
const res = await fetch(url, reqInit)
return await res.json<T>()
} catch (err) {
throw new Error(err)
}
}
let res = this.withCache(cacheKey, strategy, async () => {
let cacheControlHeader = generateCacheControlHeader(strategy)
let response = await fetch(url, {
...reqInit,
headers: {
'Cache-Control': cacheControlHeader,
'Cache-Control': generateCacheControlHeader(strategy),
...reqInit.headers,
},
})

if (!response.ok) {
let error = await response.text()
let { status, statusText } = response
throw new Error(`${status} ${statusText} ${error}`)
}

return await response.json<T>()
})
return res as Promise<T>
Expand Down

0 comments on commit e0bc85a

Please sign in to comment.