Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export class imageProcessador{
- constructor(
- private userRequest: Request
- ){}
- process(){
- const url = new URL(this.userRequest.url);
- const options = {
- cf: {
- image: {
- }
- }
- }
- if (url.searchParams.has("fit")) options.cf.image.fit = url.searchParams.get("fit")
- if (url.searchParams.has("width")) options.cf.image.width = url.searchParams.get("width")
- if (url.searchParams.has("height")) options.cf.image.height = url.searchParams.get("height")
- if (url.searchParams.has("quality")) options.cf.image.quality = url.searchParams.get("quality")
- const accept : string = this.userRequest.headers.get("Accept") || '';
- if (/image\/avif/.test(accept)) {
- options.cf.image.format = 'avif';
- } else if (/image\/webp/.test(accept)) {
- options.cf.image.format = 'webp';
- }
- const imageURL = url.searchParams.get("image")
- if (!imageURL) return new Response('Missing "image" value', { status: 400 })
- try {
- const { hostname, pathname } = new URL(imageURL)
- if (!/\.(jpe?g|png|gif|webp)$/i.test(pathname)) {
- return new Response('Disallowed file extension', { status: 400 })
- }
- if (hostname !== 'example.com') {
- return new Response('Must use "example.com" source images', { status: 403 })
- }
- } catch (err) {
- return new Response('Invalid "image" value', { status: 400 })
- }
- const imageRequest = new Request(imageURL, {
- headers: this.userRequest.headers
- })
- fetch(imageRequest, options)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment