Created
November 12, 2018 22:45
-
-
Save paulogdm/8b3a5d998fc7f96d6af80421a2e3f135 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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