1
1
#! /usr/bin/env node
2
2
const fetch = require ( 'node-fetch' ) ;
3
3
const fs = require ( 'fs' ) ;
4
-
5
-
6
4
const jsonToGo = require ( '../vendor/json-to-go/json-to-go.js' ) ;
7
5
8
- if ( process . argv . length !== 3 ) {
9
- console . log ( "parameter is wrong." )
10
- return
6
+ function run ( ) {
7
+ if ( process . argv . length !== 3 ) {
8
+ console . log ( "parameter is wrong." )
9
+ return
10
+ }
11
+
12
+ const apiUrl = process . argv [ 2 ] . replace ( / \/ $ / , '' )
13
+ fetch ( apiUrl )
14
+ . then ( res => res . json ( ) )
15
+ . then ( json => {
16
+ let res = jsonToGo ( JSON . stringify ( json ) , 'AutoGenerated' ) ;
17
+ const url = new URL ( apiUrl ) ;
18
+ const path = _parsePath ( `${ url . hostname } ${ url . pathname } ` )
19
+ const content = _buildContent ( res . go , path . pkg )
20
+ fs . mkdirSync ( path . dir , { recursive : true } )
21
+ fs . writeFile ( path . filePath , content , ( err ) => {
22
+ if ( err ) throw err ;
23
+ console . log ( `generated: ${ path . filePath } ` ) ;
24
+ } ) ;
25
+ }
26
+ ) ;
11
27
}
12
28
13
- fetch ( process . argv [ 2 ] )
14
- . then ( res => res . json ( ) )
15
- . then ( json => {
16
- let res = jsonToGo ( JSON . stringify ( json ) , 'AutoGenerated' ) ;
17
- fs . writeFile ( "hoge.go" , res . go , ( err ) => {
18
- if ( err ) throw err ;
19
- console . log ( 'generated.' ) ;
20
- } ) ;
21
- return console . log ( res . go ) ;
22
- }
23
- ) ;
29
+ function _parsePath ( path ) {
30
+ const pathArr = path . split ( "/" )
31
+ const file = pathArr [ pathArr . length - 1 ] + ".go"
32
+ const pkg = pathArr [ pathArr . length - 2 ]
33
+ pathArr . pop ( )
34
+ const dir = pathArr . join ( "/" )
35
+ return {
36
+ file,
37
+ pkg,
38
+ dir,
39
+ filePath :`${ dir } /${ file } `
40
+ }
41
+ }
24
42
43
+ function _buildContent ( struct , packageName ) {
44
+ let content = `package ${ packageName } \n\n`
45
+ if ( struct . indexOf ( 'time.' ) ) {
46
+ content = `${ content } import "time"\n\n`
47
+ }
48
+ content = `${ content } ${ struct } `
49
+ return content
50
+ }
25
51
52
+ run ( )
0 commit comments