feat: g2 ssr

This commit is contained in:
ulleo
2025-07-30 10:30:00 +08:00
parent 2827b78cd2
commit 5e13f87519
2 changed files with 41 additions and 23 deletions
+40 -23
View File
@@ -3,6 +3,10 @@ const url = require("url");
const util = require('util');
const { createChart } = require('@antv/g2-ssr');
const port = 3000;
const { getPieOptions } = require('./charts/pie.js');
const { getLineOptions } = require('./charts/line.js');
const { getColumnOptions } = require('./charts/column.js');
const { getBarOptions } = require('./charts/bar.js');
http.createServer((req, res) => {
res.statusCode = 200,
@@ -16,49 +20,62 @@ http.createServer((req, res) => {
console.log(`Server listening on: http://localhost:${port}`);
});
// 创建 Chart 和配置
async function GenerateCharts(obj) {
const options = JSON.parse(obj.options || "{}") || {
function getOptions(type, axis, data) {
const base_options = {
width: 640,
height: 480,
imageType: 'png', // or 'jpeg'
// 其他的配置透传 G2 Spec,可以参考 G2 的配置文档
type: 'interval',
data: [
{ genre: ' UIUI看看', sold: 278 },
{ genre: 'Strategy', sold: 115 },
{ genre: 'Action', sold: 120 },
{ genre: 'Shooter', sold: 350 },
{ genre: 'Other', sold: 150 },
],
encode: {
x: 'genre',
y: 'sold',
color: 'genre',
},
imageType: 'png',
theme: {
view: {
viewFill: '#FFFFFF',
},
}
}
switch (type) {
case 'bar':
return getBarOptions(base_options, axis, data);
case 'column':
return getColumnOptions(base_options, axis, data);
case 'line':
return getLineOptions(base_options, axis, data);
case 'pie':
return getPieOptions(base_options, axis, data);
}
return base_options
}
// 创建 Chart 和配置
async function GenerateCharts(obj) {
console.log(obj)
const options = getOptions(obj.type, JSON.parse(obj.axis), JSON.parse(obj.data));
console.log(options);
const chart = await createChart(options);
// 导出
chart.exportToFile(obj.id || 'chart');
chart.exportToFile(obj.path || 'chart');
// -> chart.png
chart.toBuffer();
}
// -> get buffer
//获取GET请求内容
//获取GET请求内容
function toGet(req, res) {
let data = 'GET请求内容:\n' + util.inspect(url.parse(req.url));
res.end(data);
console.log(data);
}
//获取POST请求内容、cookie
//获取POST请求内容、cookie
function toPost(req, res) {
req.on('data', function (chunk) {
GenerateCharts(JSON.parse(chunk))
req.on('data', async function (chunk) {
await GenerateCharts(JSON.parse(chunk))
res.end('complete');
});
}
+1
View File
@@ -6,6 +6,7 @@
"@antv/g2": "^5.3.3",
"@antv/g2-ssr": "^0.1.0",
"@rollup/plugin-json": "^6.1.0",
"lodash": "^4.17.21",
"nan": "^2.22.2",
"node-canvas": "^2.9.0",
"nprogress": "^0.2.0"