foxy-moxy/server.js

57 lines
1.4 KiB
JavaScript
Raw Normal View History

2017-06-13 01:39:14 +00:00
const express = require('express')
const connectDatadog = require('connect-datadog')
2017-06-13 01:39:14 +00:00
const uuid = require('uuid/v4')
const sanitize = require('sanitize-filename')
const Canvas = require('canvas')
2016-12-16 18:05:14 +00:00
2017-06-13 01:39:14 +00:00
const Fox = require('./js/fox.js')
const renderFox = require('./js/render-fox.js')
2016-12-15 19:24:22 +00:00
2017-06-14 01:37:52 +00:00
function composeImage (width, height, seed, version) {
2017-06-13 01:39:14 +00:00
seed = seed || uuid()
2018-10-19 21:29:06 +00:00
const fox = Fox(width, height, seed)
const canvas = Canvas.createCanvas(width, height)
2017-06-13 01:39:14 +00:00
renderFox(canvas, fox)
return canvas
2017-06-14 01:37:52 +00:00
}
2017-05-03 23:06:47 +00:00
2017-06-14 01:37:52 +00:00
function getFox (req, res, version) {
2017-06-13 01:39:14 +00:00
let width = parseInt(req.params.width) || 400
if (width > 400) width = 400
const seed = sanitize(req.params.seed) || uuid()
const etag = `W/${seed}`
const contentType = 'image/png'
res.set('Cache-Control', 'public; max-age=' + cacheTimeout)
res.set('Content-Type', contentType)
res.set('Etag', etag)
if (req.headers['if-none-match'] === etag) {
res.status(304).end('')
return
}
2017-06-14 01:37:52 +00:00
const canvas = composeImage(width, width, seed, version)
const buffer = canvas.toBuffer(contentType)
res.set('Content-Length', buffer.length)
2017-06-13 01:39:14 +00:00
res.end(buffer, 'binary')
2017-06-14 01:37:52 +00:00
}
const cacheTimeout = 60 * 60 * 24 * 30
const app = express()
app.use(connectDatadog({stat: 'foxy-moxy'}))
2017-06-14 01:37:52 +00:00
app.get('/healthcheck', (req, res) => {
res.status(200).end()
})
app.get('/:width/:seed', (req, res) => {
2018-10-19 21:29:06 +00:00
getFox(req, res)
2017-06-14 01:37:52 +00:00
})
app.get('/2/:width/:seed', (req, res) => {
2018-10-19 21:29:06 +00:00
getFox(req, res)
2017-06-13 01:39:14 +00:00
})
module.exports = app