1
- import type { Context } from 'hono'
1
+ import { Hono } from 'hono'
2
+ import { cors } from 'hono/cors'
2
3
import { CACHE_TTL_BY_STATUS , type Env } from '../utils/constants'
3
4
import { urlToCFI } from '../utils/cloudflare-images'
5
+ import { allowedOrigin } from '../utils/cors'
6
+ import { ResponseType } from '../utils/types'
4
7
5
- type HonoInterface = Context <
6
- {
7
- Bindings : Env
8
- } ,
9
- '/type/url' ,
10
- { }
11
- >
8
+ const app = new Hono < { Bindings : Env } > ( )
12
9
13
10
export const encodeEndpoint = ( endpoint : string ) => {
14
- // return encodeURIComponent(endpoint);
15
11
return endpoint . replace ( / [: ,._ / ] / g, '-' )
16
12
}
17
13
18
- export const getTypeUrl = async ( c : HonoInterface ) => {
14
+ app . use ( '/*' , cors ( { origin : allowedOrigin } ) )
15
+
16
+ app . get ( '/*' , async ( c ) => {
19
17
const { endpoint } = c . req . query ( )
20
18
const path = encodeEndpoint ( endpoint )
19
+ const isHead = c . req . method === 'HEAD'
21
20
22
21
// 1. check existing image on cf-images
23
22
// ----------------------------------------
@@ -27,7 +26,7 @@ export const getTypeUrl = async (c: HonoInterface) => {
27
26
cf : CACHE_TTL_BY_STATUS ,
28
27
} )
29
28
30
- if ( currentImage . ok ) {
29
+ if ( currentImage . ok && ! isHead ) {
31
30
return c . redirect ( cfImage , 302 )
32
31
}
33
32
@@ -55,7 +54,7 @@ export const getTypeUrl = async (c: HonoInterface) => {
55
54
imageAccount : c . env . CF_IMAGE_ACCOUNT ,
56
55
} )
57
56
58
- if ( imageUrl ) {
57
+ if ( imageUrl && ! isHead ) {
59
58
return c . redirect ( imageUrl , 302 )
60
59
}
61
60
@@ -65,7 +64,7 @@ export const getTypeUrl = async (c: HonoInterface) => {
65
64
const statusCode = fetchObject . status
66
65
67
66
if ( statusCode === 200 ) {
68
- await c . env . MY_BUCKET . put ( objectName , fetchObject . body , {
67
+ await c . env . MY_BUCKET . put ( objectName , fetchObject . body as ResponseType , {
69
68
httpMetadata : fetchObject . headers ,
70
69
} )
71
70
@@ -86,4 +85,6 @@ export const getTypeUrl = async (c: HonoInterface) => {
86
85
// 5. if all else fails, redirect to original endpoint
87
86
// ----------------------------------------
88
87
return c . redirect ( endpoint , 302 )
89
- }
88
+ } )
89
+
90
+ export default app
0 commit comments