Created
October 10, 2017 18:30
-
-
Save jbmoelker/d735573f9f5fb049d894f4ea2e13132c to your computer and use it in GitHub Desktop.
Serve placeholder images with Client Hints (DPR, Width, Viewport Width) as text
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
const request = require('request') | |
module.exports = () => (req, res, next) => { | |
const dpr = parseFloat(req.headers.dpr) | |
const width = toInteger(req.headers.width) | |
const viewportWidth = toInteger(req.headers['viewport-width']) | |
const imageWidth = width || Math.round(viewportWidth * dpr) | |
const imageHeight = Math.round(imageWidth/2) | |
request(`http://via.placeholder.com/${imageWidth}x${imageHeight}?text=` + [ | |
`DPR: ${dpr}`, | |
`W: ${width ? width : '?'}`, | |
`VPW: ${viewportWidth}` | |
].join(', ')) | |
.pipe(res) | |
} | |
function toInteger(value) { | |
const int = parseInt(value, 10) | |
return isNaN(int) ? undefined : int | |
} |
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
const clientHintsAsImage = require('./client-hints-as-image'); | |
const express = require('express'); | |
const app = express(); | |
app.use(/.*\.(jpg|png)/, clientHintsAsImage()); | |
app.listen(process.env.PORT); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment