@@ -3,6 +3,10 @@ const url = require("url");
33const util = require ( 'util' ) ;
44const { createChart } = require ( '@antv/g2-ssr' ) ;
55const port = 3000 ;
6+ const { getPieOptions } = require ( './charts/pie.js' ) ;
7+ const { getLineOptions } = require ( './charts/line.js' ) ;
8+ const { getColumnOptions } = require ( './charts/column.js' ) ;
9+ const { getBarOptions } = require ( './charts/bar.js' ) ;
610
711http . createServer ( ( req , res ) => {
812 res . statusCode = 200 ,
@@ -16,49 +20,62 @@ http.createServer((req, res) => {
1620 console . log ( `Server listening on: http://localhost:${ port } ` ) ;
1721} ) ;
1822
19- // 创建 Chart 和配置
20- async function GenerateCharts ( obj ) {
21- const options = JSON . parse ( obj . options || "{}" ) || {
23+ function getOptions ( type , axis , data ) {
24+
25+ const base_options = {
2226 width : 640 ,
2327 height : 480 ,
24- imageType : 'png' , // or 'jpeg'
25- // 其他的配置透传 G2 Spec,可以参考 G2 的配置文档
26- type : 'interval' ,
27- data : [
28- { genre : ' UIUI看看' , sold : 278 } ,
29- { genre : 'Strategy' , sold : 115 } ,
30- { genre : 'Action' , sold : 120 } ,
31- { genre : 'Shooter' , sold : 350 } ,
32- { genre : 'Other' , sold : 150 } ,
33- ] ,
34- encode : {
35- x : 'genre' ,
36- y : 'sold' ,
37- color : 'genre' ,
38- } ,
28+ imageType : 'png' ,
29+ theme : {
30+ view : {
31+ viewFill : '#FFFFFF' ,
32+ } ,
33+ }
3934 }
35+
36+ switch ( type ) {
37+ case 'bar' :
38+ return getBarOptions ( base_options , axis , data ) ;
39+ case 'column' :
40+ return getColumnOptions ( base_options , axis , data ) ;
41+ case 'line' :
42+ return getLineOptions ( base_options , axis , data ) ;
43+ case 'pie' :
44+ return getPieOptions ( base_options , axis , data ) ;
45+ }
46+
47+ return base_options
48+ }
49+
50+
51+ // 创建 Chart 和配置
52+ async function GenerateCharts ( obj ) {
53+ console . log ( obj )
54+ const options = getOptions ( obj . type , JSON . parse ( obj . axis ) , JSON . parse ( obj . data ) ) ;
55+ console . log ( options ) ;
4056 const chart = await createChart ( options ) ;
4157
4258 // 导出
43- chart . exportToFile ( obj . id || 'chart' ) ;
59+ chart . exportToFile ( obj . path || 'chart' ) ;
4460 // -> chart.png
4561
4662 chart . toBuffer ( ) ;
4763}
64+
4865// -> get buffer
4966
5067
51- //获取GET请求内容
68+ //获取GET请求内容
5269function toGet ( req , res ) {
5370 let data = 'GET请求内容:\n' + util . inspect ( url . parse ( req . url ) ) ;
5471 res . end ( data ) ;
5572 console . log ( data ) ;
5673}
5774
58- //获取POST请求内容、cookie
75+ //获取POST请求内容、cookie
5976function toPost ( req , res ) {
60- req . on ( 'data' , function ( chunk ) {
61- GenerateCharts ( JSON . parse ( chunk ) )
77+ req . on ( 'data' , async function ( chunk ) {
78+ await GenerateCharts ( JSON . parse ( chunk ) )
6279 res . end ( 'complete' ) ;
6380 } ) ;
6481}
0 commit comments