1- import type { Context } from 'hono'
1+ import { Hono } from 'hono'
2+ import { cors } from 'hono/cors'
23import { CACHE_TTL_BY_STATUS , type Env } from '../utils/constants'
34import { urlToCFI } from '../utils/cloudflare-images'
5+ import { allowedOrigin } from '../utils/cors'
6+ import { ResponseType } from '../utils/types'
47
5- type HonoInterface = Context <
6- {
7- Bindings : Env
8- } ,
9- '/type/url' ,
10- { }
11- >
8+ const app = new Hono < { Bindings : Env } > ( )
129
1310export const encodeEndpoint = ( endpoint : string ) => {
14- // return encodeURIComponent(endpoint);
1511 return endpoint . replace ( / [: ,._ / ] / g, '-' )
1612}
1713
18- export const getTypeUrl = async ( c : HonoInterface ) => {
14+ app . use ( '/*' , cors ( { origin : allowedOrigin } ) )
15+
16+ app . get ( '/*' , async ( c ) => {
1917 const { endpoint } = c . req . query ( )
2018 const path = encodeEndpoint ( endpoint )
19+ const isHead = c . req . method === 'HEAD'
2120
2221 // 1. check existing image on cf-images
2322 // ----------------------------------------
@@ -27,7 +26,7 @@ export const getTypeUrl = async (c: HonoInterface) => {
2726 cf : CACHE_TTL_BY_STATUS ,
2827 } )
2928
30- if ( currentImage . ok ) {
29+ if ( currentImage . ok && ! isHead ) {
3130 return c . redirect ( cfImage , 302 )
3231 }
3332
@@ -55,7 +54,7 @@ export const getTypeUrl = async (c: HonoInterface) => {
5554 imageAccount : c . env . CF_IMAGE_ACCOUNT ,
5655 } )
5756
58- if ( imageUrl ) {
57+ if ( imageUrl && ! isHead ) {
5958 return c . redirect ( imageUrl , 302 )
6059 }
6160
@@ -65,7 +64,7 @@ export const getTypeUrl = async (c: HonoInterface) => {
6564 const statusCode = fetchObject . status
6665
6766 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 , {
6968 httpMetadata : fetchObject . headers ,
7069 } )
7170
@@ -86,4 +85,6 @@ export const getTypeUrl = async (c: HonoInterface) => {
8685 // 5. if all else fails, redirect to original endpoint
8786 // ----------------------------------------
8887 return c . redirect ( endpoint , 302 )
89- }
88+ } )
89+
90+ export default app
0 commit comments