Skip to content

Commit 1c190ab

Browse files
committed
Cache photo responses (don't hit notion API)
1 parent f2a6a93 commit 1c190ab

File tree

2 files changed

+19
-7
lines changed

2 files changed

+19
-7
lines changed

index.ts

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import { getStreamerIndex, getStreamerPhoto } from './notion'
33

44
const { preflight, corsify } = cors()
55

6+
const cache = caches.default
7+
68
const router = AutoRouter<IRequest, [Env]>({
79
before: [preflight],
810
catch: (err) => {
@@ -17,14 +19,23 @@ router.get('/streamers/index.json', async ({ url }, env) => {
1719
})
1820

1921
router.get(
20-
'/streamers/:pageId/:imgName',
21-
async ({ params: { pageId } }, env) => {
22+
'/streamers/:pageId/:imgPath+',
23+
async ({ params: { pageId, imgPath } }, env) => {
24+
const cacheKey = `https://photo/${pageId}/${imgPath}`
25+
26+
const cachedResponse = await cache.match(cacheKey)
27+
if (cachedResponse) {
28+
return cachedResponse
29+
}
30+
2231
const imgURL = await getStreamerPhoto(pageId, env)
2332
if (!imgURL) {
2433
return error(404)
2534
}
26-
const resp = await fetch(imgURL)
27-
return resp
35+
const response = await fetch(imgURL)
36+
// @ts-expect-error https://github.com/cloudflare/workerd/issues/1383
37+
await cache.put(cacheKey, response.clone())
38+
return response
2839
},
2940
)
3041

notion.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,11 @@ export async function getStreamerIndex(
3838
for (const { id, props } of pages) {
3939
props.slug = kebabCase((props.slug ?? props.name).toLowerCase())
4040

41-
const photoName = props.photo?.[0]?.name
42-
if (photoName) {
41+
const photoURL = props.photo?.[0]?.file.url
42+
if (photoURL) {
4343
const { origin } = new URL(url)
44-
props.photo = `${origin}/streamers/${id}/${photoName}`
44+
const { pathname: photoPath } = new URL(photoURL)
45+
props.photo = `${origin}/streamers/${id}${photoPath}`
4546
} else {
4647
props.photo = null
4748
}

0 commit comments

Comments
 (0)