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