foxy-moxy/server.js

47 lines
1.2 KiB
JavaScript
Raw Normal View History

2016-12-19 23:52:20 +00:00
try {
const newrelic = require('newrelic');
} catch (e) {
console.error("WARNING unable to load newrelic")
}
2016-12-16 18:05:14 +00:00
var fs = require('fs');
var express = require('express');
2016-12-17 02:54:21 +00:00
var uuid = require('uuid/v4');
2016-12-17 03:24:17 +00:00
var sanitize = require('sanitize-filename');
2016-12-16 18:05:14 +00:00
var Canvas = require('canvas');
2016-12-15 21:23:38 +00:00
var Fox = require('./js/fox.js');
2016-12-16 18:34:37 +00:00
var renderFox = require('./js/render-fox.js');
2016-12-15 19:24:22 +00:00
2016-12-17 02:54:21 +00:00
function composeImage(width, height, seed) {
2016-12-17 03:46:38 +00:00
seed = seed || uuid();
2016-12-17 02:54:21 +00:00
var fox = Fox(width, height, seed);
var canvas = new Canvas(width, height);
var ctx = canvas.getContext('2d');
renderFox(canvas, fox);
return canvas;
};
2016-12-15 19:24:22 +00:00
var app = express();
2016-12-19 23:43:48 +00:00
var cacheTimeout = 60 * 60 * 24 * 30;
2016-12-19 23:39:09 +00:00
app.get('/healthcheck', function(req, res) {
res.status(200).end();
2016-12-19 23:39:09 +00:00
});
2016-12-17 02:54:21 +00:00
app.get('/:width/:seed', function(req, res) {
2016-12-17 03:46:38 +00:00
var width = parseInt(req.params.width) || 400;
2016-12-20 00:41:10 +00:00
if (width > 400) width = 400;
2016-12-17 03:46:38 +00:00
var seed = sanitize(req.params.seed) || uuid();
var canvas = composeImage(width, width, seed);
2016-12-19 22:22:41 +00:00
var buffer = canvas.toBuffer();
2016-12-19 23:43:48 +00:00
res.set('Cache-Control', 'max-age=' + cacheTimeout);
2016-12-19 22:22:41 +00:00
res.set('Content-length', buffer.length);
2016-12-19 21:52:32 +00:00
res.type('png');
2016-12-19 22:22:41 +00:00
res.end(buffer, 'binary');
2016-12-17 02:54:21 +00:00
});
2016-12-15 19:24:22 +00:00
app.listen(process.env.PORT || 3000);
console.log('listening on http://localhost:3000');