Guest User

Untitled

a guest
Nov 3rd, 2022
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export class imageProcessador{
  2.  
  3.     constructor(
  4.         private userRequest: Request
  5.     ){}
  6.  
  7.     process(){
  8.  
  9.         const url = new URL(this.userRequest.url);
  10.  
  11.         const options = {
  12.             cf: {
  13.                 image: {
  14.                 }
  15.             }
  16.         }
  17.  
  18.         if (url.searchParams.has("fit")) options.cf.image.fit = url.searchParams.get("fit")
  19.         if (url.searchParams.has("width")) options.cf.image.width = url.searchParams.get("width")
  20.         if (url.searchParams.has("height")) options.cf.image.height = url.searchParams.get("height")
  21.         if (url.searchParams.has("quality")) options.cf.image.quality = url.searchParams.get("quality")
  22.  
  23.         const accept : string = this.userRequest.headers.get("Accept") || '';
  24.  
  25.         if (/image\/avif/.test(accept)) {
  26.             options.cf.image.format = 'avif';
  27.         } else if (/image\/webp/.test(accept)) {
  28.             options.cf.image.format = 'webp';
  29.         }
  30.  
  31.         const imageURL = url.searchParams.get("image")
  32.         if (!imageURL) return new Response('Missing "image" value', { status: 400 })
  33.  
  34.         try {
  35.            
  36.             const { hostname, pathname } = new URL(imageURL)
  37.  
  38.             if (!/\.(jpe?g|png|gif|webp)$/i.test(pathname)) {
  39.                 return new Response('Disallowed file extension', { status: 400 })
  40.             }
  41.  
  42.             if (hostname !== 'example.com') {
  43.                 return new Response('Must use "example.com" source images', { status: 403 })
  44.             }
  45.         } catch (err) {
  46.             return new Response('Invalid "image" value', { status: 400 })
  47.         }
  48.  
  49.         const imageRequest = new Request(imageURL, {
  50.             headers: this.userRequest.headers
  51.         })
  52.  
  53.         fetch(imageRequest, options)
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment