Skip to content

Instantly share code, notes, and snippets.

@paulogdm
Created November 12, 2018 22:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulogdm/8b3a5d998fc7f96d6af80421a2e3f135 to your computer and use it in GitHub Desktop.
Save paulogdm/8b3a5d998fc7f96d6af80421a2e3f135 to your computer and use it in GitHub Desktop.
// taken from https://spectrum.chat/thread/3d15e59b-a893-494a-b8a8-a8cc391094d6
const {send} = require('micro')
const axios = require('axios')
const fs = require('fs')
const sharp = require('sharp')
const memoize = require('memoizee')
const querystring = require('querystring')
const parseUrl = (url) => {
console.log('url', url)
const [path, query] = url.split('?', 2)
const queryObj = querystring.parse(query)
return {url:`${process.env.BASE_URL || 'http://www.gamersunite.com'}${path}`, resizeWidth:queryObj.w}
}
const fetchImage = async (requestUrl)=>{
const {url, resizeWidth} = parseUrl(requestUrl)
const response = await axios({method:'get', url, responseType:'arraybuffer'})
console.log('resizeWidth',parseInt(resizeWidth,10), resizeWidth)
const buffer = await sharp(response.data).resize(parseInt(resizeWidth,10)).jpeg().toBuffer()
return buffer
}
const mFetchImage = memoize(fetchImage, 1, {primitive:true, promise: true, max:1000, maxAge:1000*60*60*24})
module.exports = async (req, res) => {
if (req.url.endsWith('.ico')) {
return send(res, 404)
}
try {
const buffer = await mFetchImage(req.url)
res.setHeader('Content-Type', 'image/jpeg')
res.write(buffer)
res.end()
}
catch(e) {
console.error('err', e.status, req.url)
return send(res, e.status)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment