UNPKG

simple-chartjs

Version:

Un module ChartJS simple d'utilisation, rapide et puissant !

118 lines (111 loc) 4.08 kB
const { ChartJSNodeCanvas } = require('chartjs-node-canvas'); const ChartJSDatalabels = require('chartjs-plugin-datalabels') class Chart { /** * @typedef {object} ChartConfig * * @property {object} identity * @property {object} identity.title * @property {string} identity.title.text * @property {string} identity.title.color * @property {object} identity.title.font * @property {number} identity.title.font.size * @property {string} identity.title.font.family * @property {object} identity.subtitle * @property {string} identity.subtitle.text * @property {string} identity.subtitle.color * @property {object} identity.subtitle.font * @property {number} identity.subtitle.font.size * @property {string} identity.subtitle.font.family * @property {'line' | 'bar' | 'radar' | 'doughnut' | 'polarArea' | 'bubble' | 'scatter'} identity.type * * @property {object} sizes * @property {number} sizes.height * @property {number} sizes.width * * @property {object} data * @property {object} data.font * @property {number} data.font.size * @property {string} data.font.family * @property {any[]} data.labels * @property {Graph[]} data.graphs * * @property {object} options * @property {string} options.backgroundColor * @property {string} options.labelsColor * @property {boolean} options.displayValues */ /** * @param {ChartConfig} config */ constructor(config) { this.width = config.sizes.width; this.height = config.sizes.height; this.title = config.identity?.title; this.subtitle = config.identity?.subtitle; this.type = config.identity?.type || undefined; this.labels = config.data.labels || []; this.graphs = config.data.graphs; this.labelsFont = config.data.font; this.backgroundColour = config.options.backgroundColor; this.labelsColor = config.options.labelsColor; this.plugins = []; if(config.options.displayValues) this.plugins.push(ChartJSDatalabels); }; /* RENDERING */ /** * @returns {Promise<Buffer>} */ async renderToBuffer() { return await this.#getCanvas().renderToBuffer(this.#renderToData()); }; /* UTIL */ /** * @returns {ChartJSNodeCanvas} */ #getCanvas() { return new ChartJSNodeCanvas({ plugins: this.plugins, type: this.type, width: this.width, height: this.height, backgroundColour: this.backgroundColour }); }; #renderToData() { return ({ plugins: this.plugins, type: this.type, data: { labels: this.labels, datasets: this.graphs }, options: { plugins: { title: { display: this.title?.text ? true : false, text: this.title.text, color: this.title.color, font: { size: this.title.font?.size, family: this.title.font?.family } }, subtitle: { display: this.subtitle?.text ? true : false, text: this.subtitle.text, color: this.subtitle.color, font: { size: this.subtitle.font?.size, family: this.subtitle.font?.family } }, legend: { labels: { color: this.labelsColor, font: this.labelsFont } } } } }) }; }; module.exports = Chart;