-
Notifications
You must be signed in to change notification settings - Fork 213
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add sources cache to Nuxt app (#5288)
* Add a server cache for sources * Use nitro `defineCachedFunction` for caching * Fix the unit test
- Loading branch information
Showing
3 changed files
with
92 additions
and
59 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
import { consola } from "consola" | ||
import { useRuntimeConfig, defineCachedFunction } from "nitropack/runtime" | ||
import { defineEventHandler, getProxyRequestHeaders, type H3Event } from "h3" | ||
|
||
import { | ||
supportedMediaTypes, | ||
type SupportedMediaType, | ||
} from "#shared/constants/media" | ||
import { userAgentHeader } from "#shared/constants/user-agent.mjs" | ||
import { mediaSlug } from "#shared/utils/query-utils" | ||
|
||
const UPDATE_FREQUENCY_SECONDS = 60 * 60 // 1 hour | ||
|
||
type Sources = { | ||
[K in SupportedMediaType]: MediaProvider[] | ||
} | ||
|
||
const getSources = defineCachedFunction( | ||
async (mediaType: SupportedMediaType, event: H3Event) => { | ||
const apiUrl = useRuntimeConfig(event).public.apiUrl | ||
|
||
consola.info(`Fetching sources for ${mediaType} media`) | ||
|
||
return await $fetch<MediaProvider[]>( | ||
`${apiUrl}v1/${mediaSlug(mediaType)}/stats/`, | ||
{ | ||
headers: { | ||
...getProxyRequestHeaders(event), | ||
...userAgentHeader, | ||
}, | ||
} | ||
) | ||
}, | ||
{ | ||
maxAge: UPDATE_FREQUENCY_SECONDS, | ||
name: "sources", | ||
getKey: (mediaType) => mediaType, | ||
} | ||
) | ||
|
||
/** | ||
* The cached function uses stale-while-revalidate (SWR) to fetch sources for each media type only once per hour. | ||
*/ | ||
export default defineEventHandler(async (event) => { | ||
const sources: Sources = { audio: [], image: [] } | ||
|
||
for (const mediaType of supportedMediaTypes) { | ||
sources[mediaType] = await getSources(mediaType, event) | ||
} | ||
|
||
return sources | ||
}) |
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
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