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')
2017-06-14 01:37:52 +00:00
const FoxAmerica = require('./js/fox-america.js')
2017-06-13 01:39:14 +00:00
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()
2017-06-14 01:37:52 +00:00
let fox
switch (version) {
case 2:
// America-color bg and fox
fox = FoxAmerica(width, height, seed)
break
default:
// original fox
fox = Fox(width, height, seed)
}
2017-06-13 01:39:14 +00:00
const canvas = new Canvas(width, height)
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()
2017-06-14 01:37:52 +00:00
const canvas = composeImage(width, width, seed, version)
2017-06-13 01:39:14 +00:00
const buffer = canvas.toBuffer()
res.set('Cache-Control', 'max-age=' + cacheTimeout)
res.set('Content-length', buffer.length)
res.type('png')
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) => {
getFox(req, res, 1)
})
app.get('/2/:width/:seed', (req, res) => {
getFox(req, res, 2)
2017-06-13 01:39:14 +00:00
})
module.exports = app