foxy-moxy/server.js

64 lines
1.8 KiB
JavaScript
Raw Permalink 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')
2019-10-15 19:05:44 +00:00
const Sentry = require('@sentry/node');
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'}))
2019-10-15 19:05:44 +00:00
Sentry.init({ dsn: 'https://46660182a19d400f9775f441ac9bcf15@sentry.io/1780766' })
// The request handler must be the first middleware on the app
app.use(Sentry.Handlers.requestHandler())
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
})
2019-10-15 19:05:44 +00:00
// The error handler must be before any other error middleware and after all controllers
app.use(Sentry.Handlers.errorHandler())
2017-06-13 01:39:14 +00:00
module.exports = app