aboutsummaryrefslogtreecommitdiff
path: root/src/resolve-request.js
blob: 75f1f111b148f74a297b46f8e7910aeec9030b69 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const notionImagePrefix = 'https://www.notion.so/image/'

/**
 * @param {*} event
 * @param {*} request
 */
export async function resolveRequest(event, request) {
  const requestUrl = new URL(request.url)
  let originUri = decodeURIComponent(requestUrl.pathname.slice(1))

  // special-case optimization for notion images coming from unsplash
  if (originUri.startsWith(notionImagePrefix)) {
    const imageUri = decodeURIComponent(
      originUri.slice(notionImagePrefix.length)
    )
    const imageUrl = new URL(imageUri)

    // adjust unsplash defaults to have a max width and intelligent format conversion
    if (imageUrl.hostname === 'images.unsplash.com') {
      const { searchParams } = imageUrl

      if (!searchParams.has('w') && !searchParams.has('fit')) {
        imageUrl.searchParams.set('w', 1920)
        imageUrl.searchParams.set('fit', 'max')
      }

      if (!searchParams.has('auto')) {
        imageUrl.searchParams.set('auto', 'format')
      }

      originUri = `${notionImagePrefix}${encodeURIComponent(
        imageUrl.toString()
      )}`
    }
  }

  const originReq = new Request(originUri, request)

  return { originReq }
}