Skip to content

Commit

Permalink
fix: memoize config CDN call (#1000)
Browse files Browse the repository at this point in the history
  • Loading branch information
ajwootto authored Nov 22, 2024
1 parent d5f148a commit 5561d8d
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 24 deletions.
12 changes: 4 additions & 8 deletions sdk/nextjs/src/server/bucketing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
BucketedConfigWithAdditionalFields,
DevCycleNextOptions,
} from '../common/types'
import { BucketedUserConfig, ConfigBody, ConfigSource } from '@devcycle/types'
import { ConfigBody, ConfigSource } from '@devcycle/types'

const getPopulatedUser = cache((user: DevCycleUser, userAgent?: string) => {
return new DVCPopulatedUser(
Expand Down Expand Up @@ -67,18 +67,14 @@ class CDNConfigSource extends ConfigSource {
}
async getConfig(sdkKey: string, kind: string, obfuscated: boolean) {
// this request will be cached by Next
const cdnConfig = await fetchCDNConfig(
const { config, headers } = await fetchCDNConfig(
sdkKey,
this.clientSDKKey,
obfuscated,
)
if (!cdnConfig.ok) {
const responseText = await cdnConfig.text()
throw new Error('Could not fetch config: ' + responseText)
}
return {
config: (await cdnConfig.json()) as ConfigBody,
lastModified: cdnConfig.headers.get('last-modified'),
config: config,
lastModified: headers.get('last-modified'),
metaData: {},
}
}
Expand Down
43 changes: 27 additions & 16 deletions sdk/nextjs/src/server/requests.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,40 @@
import { DVCPopulatedUser } from '@devcycle/js-client-sdk'
import { serializeUserSearchParams } from '../common/serializeUser'
import { cache } from 'react'
import { BucketedUserConfig } from '@devcycle/types'
import { BucketedUserConfig, ConfigBody } from '@devcycle/types'

const getFetchUrl = (sdkKey: string, obfuscated: boolean) =>
`https://config-cdn.devcycle.com/config/v2/server/bootstrap/${
obfuscated ? 'obfuscated/' : ''
}${sdkKey}.json`

export const fetchCDNConfig = async (
sdkKey: string,
clientSDKKey: string,
obfuscated: boolean,
): Promise<Response> => {
return await fetch(
getFetchUrl(sdkKey, obfuscated),
// only store for 60 seconds
{
next: {
revalidate: 60,
tags: [sdkKey, clientSDKKey],
export const fetchCDNConfig = cache(
async (
sdkKey: string,
clientSDKKey: string,
obfuscated: boolean,
): Promise<{ config: ConfigBody; headers: Headers }> => {
const response = await fetch(
getFetchUrl(sdkKey, obfuscated),
// only store for 60 seconds
{
next: {
revalidate: 60,
tags: [sdkKey, clientSDKKey],
},
},
},
)
}
)

if (!response.ok) {
const responseText = await response.text()
throw new Error('Could not fetch config: ' + responseText)
}
return {
config: (await response.json()) as ConfigBody,
headers: response.headers,
}
},
)

const getSDKAPIUrl = (
sdkKey: string,
Expand Down

0 comments on commit 5561d8d

Please sign in to comment.