1
1
#! /usr/bin/env node
2
- const fetch = require ( 'node-fetch ' ) ;
3
- const fs = require ( 'fs ' ) ;
4
- const jsonToGo = require ( '../vendor/json-to-go.js' ) ;
5
- const buildPath = require ( '../src/buildPath ' ) ;
2
+ const run = require ( '../src/run ' ) ;
3
+ const { Command } = require ( 'commander ' ) ;
4
+ const program = new Command ( ) ;
5
+ const packageJson = require ( '../package.json ' ) ;
6
6
7
- function run ( url ) {
8
- const apiUrl = url . replace ( / \/ $ / , '' )
9
- fetch ( apiUrl )
10
- . then ( res => res . json ( ) )
11
- . then ( json => {
12
- const url = new URL ( apiUrl ) ;
13
- const path = buildPath ( url )
14
- const res = jsonToGo ( JSON . stringify ( json ) , path . struct ) ;
15
- const content = _buildContent ( res . go , path , url )
16
- fs . mkdirSync ( path . dir , { recursive : true } )
17
- fs . writeFile ( path . jsonFilePath , JSON . stringify ( json , null , "\t" ) , ( err ) => {
18
- if ( err ) throw err ;
19
- console . log ( `saved: ${ path . jsonFilePath } ` )
20
- } ) ;
21
- fs . writeFile ( path . goFilePath , content , ( err ) => {
22
- if ( err ) throw err ;
23
- console . log ( `generated: ${ path . goFilePath } ` )
24
- } ) ;
25
- }
26
- ) ;
27
- }
7
+ // See: https://github.com/tj/commander.js
8
+ program
9
+ . name ( 'api-to-go' )
10
+ . version ( packageJson . version , '-v, --version' , 'output the current version' )
11
+ . description ( packageJson . description )
12
+ . argument ( '<url>' , 'URL (required)' )
13
+ . argument ( '[body]' , 'HTTP request body. specify by json string or file(json|yml).' )
14
+ . option ( '-H, --headers <string>' , 'http request headers. specify by json string or file(json|yml).' )
15
+ . option ( '-X, --method <string>' , 'specify request method to use.' )
16
+ . option ( '--config <string>' , 'location of client config files.' , "./.api-to-go.yml" )
17
+ . option ( '-D, --debug' , 'enable debug mode' )
18
+ . action ( run )
28
19
29
- function _buildContent ( struct , path , url ) {
30
- let content = `package ${ path . pkg } \n\n`
31
- if ( struct . indexOf ( 'time.' ) !== - 1 ) {
32
- content = `${ content } import "time"\n\n`
33
- }
34
- let comment = `// ${ path . struct } is the go struct of api's payload.`
35
- if ( path . path . pathFormat ) {
36
- comment += `\n//\n// url: ${ url . origin } ${ path . path . pathFormat } `
37
- comment += `\n// example: ${ url . href } `
38
- } else {
39
- comment += `\n//\n// url: ${ url . href } `
40
- }
41
- content = `${ content } ${ comment } \n//\n${ struct } `
42
- return content
43
- }
44
-
45
- function _capitalize ( str ) {
46
- const lower = str . toLowerCase ( ) ;
47
- return str . charAt ( 0 ) . toUpperCase ( ) + lower . slice ( 1 ) ;
48
- }
49
-
50
- if ( process . argv . length !== 3 ) {
51
- console . log ( "parameter is wrong." )
52
- return
53
- }
54
-
55
- run ( process . argv [ 2 ] )
20
+ program . parse ( ) ;
0 commit comments