94 lines
2.3 KiB
JavaScript
94 lines
2.3 KiB
JavaScript
const { createCanvas } = require("canvas");
|
|
const Chart = require("chart.js/auto");
|
|
const logger = require("../utils/logger");
|
|
|
|
const { backgroundColors, borderColors } = require("./canvas-colors");
|
|
const { isObject, defaultsDeep, isNumber } = require("lodash");
|
|
|
|
exports.canvastest = function (req, res) {
|
|
//console.log("Incoming test request.", req);
|
|
res.status(200).send("OK");
|
|
};
|
|
|
|
exports.canvas = function (req, res) {
|
|
const { w, h, values, keys, override } = req.body;
|
|
//console.log("Incoming Canvas Request:", w, h, values, keys, override);
|
|
logger.log("inbound-canvas-creation", "debug", "jsr", null, { w, h, values, keys, override });
|
|
// Gate required values
|
|
if (!values || !keys) {
|
|
res.status(400).send("Missing required data");
|
|
return;
|
|
}
|
|
|
|
// Override must be an object if it exists
|
|
if (override && !isObject(override)) {
|
|
res.status(400).send("Override must be an object");
|
|
return;
|
|
}
|
|
|
|
// Set the default Width and Height
|
|
let [width, height] = [500, 275];
|
|
|
|
// Allow for custom width and height
|
|
if (isNumber(w)) {
|
|
width = w;
|
|
}
|
|
if (isNumber(h)) {
|
|
height = h;
|
|
}
|
|
|
|
const configuration = {
|
|
type: "doughnut",
|
|
data: {
|
|
labels: keys,
|
|
datasets: [
|
|
{
|
|
data: values,
|
|
backgroundColor: backgroundColors,
|
|
borderColor: borderColors,
|
|
borderWidth: 1
|
|
}
|
|
]
|
|
},
|
|
options: {
|
|
devicePixelRatio: 4,
|
|
responsive: false,
|
|
maintainAspectRatio: true,
|
|
circumference: 180,
|
|
rotation: -90,
|
|
plugins: {
|
|
legend: {
|
|
labels: {
|
|
boxWidth: 20,
|
|
font: {
|
|
family: "'Montserrat'",
|
|
size: 10,
|
|
style: "normal",
|
|
weight: "normal"
|
|
}
|
|
},
|
|
position: "left"
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
// If we have a valid override object, merge it with the default configuration object.
|
|
// This allows for you to override the default configuration with a custom one.
|
|
const defaults = () => {
|
|
if (!override || !isObject(override)) {
|
|
return configuration;
|
|
}
|
|
return defaultsDeep(override, configuration);
|
|
};
|
|
|
|
res.status(200).send(
|
|
(() => {
|
|
const canvas = createCanvas(width, height);
|
|
const ctx = canvas.getContext("2d");
|
|
new Chart(ctx, defaults());
|
|
return canvas.toDataURL();
|
|
})()
|
|
);
|
|
};
|