Skip to content

Commit 048b63a

Browse files
committed
✨ Add feature that path format setting.
1 parent 3ba7d3a commit 048b63a

File tree

4 files changed

+178
-71
lines changed

4 files changed

+178
-71
lines changed

README.md

Lines changed: 119 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -11,44 +11,133 @@ yarn setup
1111
```
1212

1313
# Usage
14+
add config file `.api-to-go.yaml`.
15+
```yaml
16+
api.github.com:
17+
- /users/{user}/repos
18+
```
19+
run command.
1420
```sh
1521
cd [your project dir]
16-
api-to-go https://api.github.com/users
17-
# > ...
18-
# > saved: api.github.com/users_sample.json
19-
# > generated: api.github.com/users.go
22+
api-to-go https://api.github.com/users/github/repos
23+
# > replaced : /users/github/repos -> /users/{user}/repos -> /users/user/repos
24+
# > generated: api.github.com/users/user/repos.go
25+
# > saved: api.github.com/users/user/repos_sample.json
2026
```
21-
27+
check generated files and directories.
2228
```sh
23-
tree .
29+
tree -a .
2430
# > .
31+
# > ├── .api-to-go.yaml
2532
# > └── api.github.com
26-
# > ├── users.go
27-
# > └── users_sample.json
33+
# > └── users
34+
# > └── user
35+
# > ├── repos.go
36+
# > └── repos_sample.json
2837
```
29-
38+
check generated struct file `./api.github.com/users/user/repos.go`.
3039
```go
31-
// ./api.github.com/users.go
32-
package apigithubcom
40+
package user
3341

34-
type Users []struct {
35-
Login string `json:"login"`
36-
ID int `json:"id"`
37-
NodeID string `json:"node_id"`
38-
AvatarURL string `json:"avatar_url"`
39-
GravatarID string `json:"gravatar_id"`
40-
URL string `json:"url"`
41-
HTMLURL string `json:"html_url"`
42-
FollowersURL string `json:"followers_url"`
43-
FollowingURL string `json:"following_url"`
44-
GistsURL string `json:"gists_url"`
45-
StarredURL string `json:"starred_url"`
46-
SubscriptionsURL string `json:"subscriptions_url"`
47-
OrganizationsURL string `json:"organizations_url"`
48-
ReposURL string `json:"repos_url"`
49-
EventsURL string `json:"events_url"`
50-
ReceivedEventsURL string `json:"received_events_url"`
51-
Type string `json:"type"`
52-
SiteAdmin bool `json:"site_admin"`
42+
import "time"
43+
44+
type Repos []struct {
45+
ID int `json:"id"`
46+
NodeID string `json:"node_id"`
47+
Name string `json:"name"`
48+
FullName string `json:"full_name"`
49+
Private bool `json:"private"`
50+
Owner Owner `json:"owner"`
51+
HTMLURL string `json:"html_url"`
52+
Description string `json:"description"`
53+
Fork bool `json:"fork"`
54+
URL string `json:"url"`
55+
ForksURL string `json:"forks_url"`
56+
KeysURL string `json:"keys_url"`
57+
CollaboratorsURL string `json:"collaborators_url"`
58+
TeamsURL string `json:"teams_url"`
59+
HooksURL string `json:"hooks_url"`
60+
IssueEventsURL string `json:"issue_events_url"`
61+
EventsURL string `json:"events_url"`
62+
AssigneesURL string `json:"assignees_url"`
63+
BranchesURL string `json:"branches_url"`
64+
TagsURL string `json:"tags_url"`
65+
BlobsURL string `json:"blobs_url"`
66+
GitTagsURL string `json:"git_tags_url"`
67+
GitRefsURL string `json:"git_refs_url"`
68+
TreesURL string `json:"trees_url"`
69+
StatusesURL string `json:"statuses_url"`
70+
LanguagesURL string `json:"languages_url"`
71+
StargazersURL string `json:"stargazers_url"`
72+
ContributorsURL string `json:"contributors_url"`
73+
SubscribersURL string `json:"subscribers_url"`
74+
SubscriptionURL string `json:"subscription_url"`
75+
CommitsURL string `json:"commits_url"`
76+
GitCommitsURL string `json:"git_commits_url"`
77+
CommentsURL string `json:"comments_url"`
78+
IssueCommentURL string `json:"issue_comment_url"`
79+
ContentsURL string `json:"contents_url"`
80+
CompareURL string `json:"compare_url"`
81+
MergesURL string `json:"merges_url"`
82+
ArchiveURL string `json:"archive_url"`
83+
DownloadsURL string `json:"downloads_url"`
84+
IssuesURL string `json:"issues_url"`
85+
PullsURL string `json:"pulls_url"`
86+
MilestonesURL string `json:"milestones_url"`
87+
NotificationsURL string `json:"notifications_url"`
88+
LabelsURL string `json:"labels_url"`
89+
ReleasesURL string `json:"releases_url"`
90+
DeploymentsURL string `json:"deployments_url"`
91+
CreatedAt time.Time `json:"created_at"`
92+
UpdatedAt time.Time `json:"updated_at"`
93+
PushedAt time.Time `json:"pushed_at"`
94+
GitURL string `json:"git_url"`
95+
SSHURL string `json:"ssh_url"`
96+
CloneURL string `json:"clone_url"`
97+
SvnURL string `json:"svn_url"`
98+
Homepage interface{} `json:"homepage"`
99+
Size int `json:"size"`
100+
StargazersCount int `json:"stargazers_count"`
101+
WatchersCount int `json:"watchers_count"`
102+
Language interface{} `json:"language"`
103+
HasIssues bool `json:"has_issues"`
104+
HasProjects bool `json:"has_projects"`
105+
HasDownloads bool `json:"has_downloads"`
106+
HasWiki bool `json:"has_wiki"`
107+
HasPages bool `json:"has_pages"`
108+
ForksCount int `json:"forks_count"`
109+
MirrorURL interface{} `json:"mirror_url"`
110+
Archived bool `json:"archived"`
111+
Disabled bool `json:"disabled"`
112+
OpenIssuesCount int `json:"open_issues_count"`
113+
License interface{} `json:"license"`
114+
AllowForking bool `json:"allow_forking"`
115+
IsTemplate bool `json:"is_template"`
116+
Topics []interface{} `json:"topics"`
117+
Visibility string `json:"visibility"`
118+
Forks int `json:"forks"`
119+
OpenIssues int `json:"open_issues"`
120+
Watchers int `json:"watchers"`
121+
DefaultBranch string `json:"default_branch"`
122+
}
123+
type Owner struct {
124+
Login string `json:"login"`
125+
ID int `json:"id"`
126+
NodeID string `json:"node_id"`
127+
AvatarURL string `json:"avatar_url"`
128+
GravatarID string `json:"gravatar_id"`
129+
URL string `json:"url"`
130+
HTMLURL string `json:"html_url"`
131+
FollowersURL string `json:"followers_url"`
132+
FollowingURL string `json:"following_url"`
133+
GistsURL string `json:"gists_url"`
134+
StarredURL string `json:"starred_url"`
135+
SubscriptionsURL string `json:"subscriptions_url"`
136+
OrganizationsURL string `json:"organizations_url"`
137+
ReposURL string `json:"repos_url"`
138+
EventsURL string `json:"events_url"`
139+
ReceivedEventsURL string `json:"received_events_url"`
140+
Type string `json:"type"`
141+
SiteAdmin bool `json:"site_admin"`
53142
}
54143
```

bin/api-to-go.js

Lines changed: 2 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,17 @@
22
const fetch = require('node-fetch');
33
const fs = require('fs');
44
const jsonToGo = require('../vendor/json-to-go/json-to-go.js');
5+
const buildPath = require('../src/buildPath');
56

67
function run(url) {
78
const apiUrl = url.replace(/\/$/, '')
89
fetch(apiUrl)
910
.then(res => res.json())
1011
.then(json => {
11-
const path = _parseUrl(apiUrl)
12+
const path = buildPath(apiUrl)
1213
const res = jsonToGo(JSON.stringify(json), path.struct);
1314
const content = _buildContent(res.go, path.pkg)
1415
fs.mkdirSync(path.dir, {recursive: true})
15-
console.log(json)
16-
console.log()
1716
fs.writeFile(path.jsonFilePath, JSON.stringify(json,null,"\t"), (err) => {
1817
if (err) throw err;
1918
console.log(`saved: ${path.jsonFilePath}`)
@@ -26,24 +25,6 @@ function run(url) {
2625
);
2726
}
2827

29-
function _parseUrl(apiUrl) {
30-
const url = new URL(apiUrl);
31-
const path = `${url.hostname}${url.pathname}`
32-
const pathArr = path.split("/")
33-
const pkg = pathArr[pathArr.length - 2].replace(/\./g, '')
34-
const last = pathArr[pathArr.length - 1] || "index"
35-
const struct = _capitalize(last)
36-
pathArr.pop()
37-
const dir = pathArr.join("/")
38-
return {
39-
struct,
40-
pkg,
41-
dir,
42-
jsonFilePath: `${dir}/${last}_sample.json`,
43-
goFilePath: `${dir}/${last}.go`
44-
}
45-
}
46-
4728
function _buildContent(struct, packageName) {
4829
let content = `package ${packageName}\n\n`
4930
if (struct.indexOf('time.') !== -1) {

src/buildPath.js

Lines changed: 47 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,16 @@ const yaml = require("js-yaml");
22
const fs = require("fs");
33

44
function buildPath(apiUrl, configFile = "./.api-to-go.yaml") {
5-
// TODO: configのパターンを検知してpathを変換
6-
75
const url = new URL(apiUrl);
8-
_buildPath(url, configFile)
9-
const path = `${url.hostname}${url.pathname}`
10-
11-
const pathArr = path.split("/")
6+
const path = _buildPath(url, configFile)
7+
const pathArr = path.replacedUrl.split("/")
128
const pkg = pathArr[pathArr.length - 2].replace(/\./g, '')
139
const last = pathArr[pathArr.length - 1] || "index"
1410
const struct = _capitalize(last)
1511
pathArr.pop()
1612
const dir = pathArr.join("/")
1713
return {
14+
path,
1815
struct,
1916
pkg,
2017
dir,
@@ -23,6 +20,50 @@ function buildPath(apiUrl, configFile = "./.api-to-go.yaml") {
2320
}
2421
}
2522

23+
function _buildPath(url, configFile) {
24+
const cfg = _loadConfig(configFile)
25+
const hostCfg = cfg?.[url.hostname]
26+
let ret;
27+
if (hostCfg !== undefined) {
28+
for (let i = 0; i < hostCfg.length; i++) {
29+
ret = _replacePath(url.pathname, hostCfg[i])
30+
if (ret) {
31+
ret["replacedUrl"] = `${url.hostname}${ret.replacedPath}`
32+
return ret
33+
}
34+
}
35+
}
36+
ret["replacedUrl"] = `${url.hostname}${url.pathname}`
37+
return ret
38+
}
39+
40+
function _replacePath(pathname, format) {
41+
const replacedArr = []
42+
const pathArr = pathname.split('/')
43+
const formatArr = format.split('/')
44+
if (pathArr.length !== formatArr.length) {
45+
return false
46+
}
47+
for (let j = 0; j < formatArr.length; j++) {
48+
if (pathArr[j] === formatArr[j]) {
49+
replacedArr.push(pathArr[j])
50+
continue
51+
}
52+
const val = formatArr[j].match(/^{.*}$/)
53+
if (val === null) {
54+
break
55+
}
56+
replacedArr.push(formatArr[j].replace("{", "").replace("}", ""))
57+
}
58+
const replacedPath = replacedArr.join("/")
59+
console.log(`replaced : ${pathname} -> ${format} -> ${replacedPath}`)
60+
return {
61+
pathname: pathname,
62+
pathFormat: format,
63+
replacedPath: replacedPath,
64+
}
65+
}
66+
2667
function _capitalize(str) {
2768
const lower = str.toLowerCase();
2869
return str.charAt(0).toUpperCase() + lower.slice(1);
@@ -36,14 +77,4 @@ function _loadConfig(configFile) {
3677
}
3778
}
3879

39-
function _buildPath(url, configFile) {
40-
const cfg = _loadConfig(configFile)
41-
const hostCfg = cfg?.[url.hostname]
42-
if (hostCfg !== undefined) {
43-
for (let i = 0; i < hostCfg.length; i++) {
44-
console.log(hostCfg[i])
45-
}
46-
}
47-
}
48-
4980
module.exports = buildPath;

src/buildPath.test.js

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,16 @@ const buildPath = require('./buildPath');
22

33
test('build path', () => {
44
const expected = {
5-
"dir": "api.github.com/users/github",
6-
"goFilePath": "api.github.com/users/github/repos.go",
7-
"jsonFilePath": "api.github.com/users/github/repos_sample.json",
8-
"pkg": "github",
5+
"dir": "api.github.com/users/user",
6+
"goFilePath": "api.github.com/users/user/repos.go",
7+
"jsonFilePath": "api.github.com/users/user/repos_sample.json",
8+
"path": {
9+
"pathFormat": "/users/{user}/repos",
10+
"pathname": "/users/github/repos",
11+
"replacedPath": "/users/user/repos",
12+
"replacedUrl": "api.github.com/users/user/repos"
13+
},
14+
"pkg": "user",
915
"struct": "Repos"
1016
}
1117
const received = buildPath(

0 commit comments

Comments
 (0)