const request = require('request')
const sharp = require('sharp')

const QUALITY = 40

module.exports = (context, req, res) => {
  const imageUrl = req.query.url
  if (!imageUrl.match(/^https?:/i)) return res.status(400).end()

  const transformer = sharp().grayscale().toFormat('webp', { quality: QUALITY })
  transformer.on('error', err => console.log(`Error in ${imageUrl}: ${err}`))
  transformer.on('data', processedImage => {
    console.log(`Compressed: ${imageUrl}`)
    res.writeHead(200, {
      'Content-Type': 'image/webp',
      'Content-Length': processedImage.length
    })
  })

  request(imageUrl).pipe(transformer).pipe(res)
}

@@ -1,12 +1,25 @@
+'use strict'%0A
 const reques
@@ -234,16 +234,43 @@
 .end()%0A%0A
+  let originalFileSize = 0%0A
   const 
@@ -592,16 +592,124 @@
 Length':
+ processedImage.length,%0A      'X-Original-Size': originalFileSize,%0A      'X-Bytes-Saved': originalFileSize -
  process
@@ -745,16 +745,25 @@
  request
+%0A    .get
 (imageUr
@@ -764,16 +764,128 @@
 mageUrl)
+%0A    .on(%0A      'response',%0A      response =%3E (originalFileSize = response.headers%5B'content-length'%5D)%0A    )%0A    
 .pipe(tr
@@ -894,16 +894,21 @@
 sformer)
+%0A    
 .pipe(re

Return how many bytes were compressed in response header.