Skip to content

Commit 8457f84

Browse files
authored
Merge pull request #1 from kahirokunn/main
2 parents d9d3fb1 + 3b94f9e commit 8457f84

File tree

6 files changed

+226
-24
lines changed

6 files changed

+226
-24
lines changed

.gitignore

+134-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,135 @@
1+
### https://raw.github.com/github/gitignore/218a941be92679ce67d0484547e3e142b2f5f6f0/Node.gitignore
2+
3+
# Logs
4+
logs
5+
*.log
6+
npm-debug.log*
7+
yarn-debug.log*
8+
yarn-error.log*
9+
lerna-debug.log*
10+
11+
# Diagnostic reports (https://nodejs.org/api/report.html)
12+
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
13+
14+
# Runtime data
15+
pids
16+
*.pid
17+
*.seed
18+
*.pid.lock
19+
20+
# Directory for instrumented libs generated by jscoverage/JSCover
21+
lib-cov
22+
23+
# Coverage directory used by tools like istanbul
24+
coverage
25+
*.lcov
26+
27+
# nyc test coverage
28+
.nyc_output
29+
30+
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
31+
.grunt
32+
33+
# Bower dependency directory (https://bower.io/)
34+
bower_components
35+
36+
# node-waf configuration
37+
.lock-wscript
38+
39+
# Compiled binary addons (https://nodejs.org/api/addons.html)
40+
build/Release
41+
42+
# Dependency directories
43+
node_modules/
44+
jspm_packages/
45+
46+
# Snowpack dependency directory (https://snowpack.dev/)
47+
web_modules/
48+
49+
# TypeScript cache
50+
*.tsbuildinfo
51+
52+
# Optional npm cache directory
53+
.npm
54+
55+
# Optional eslint cache
56+
.eslintcache
57+
58+
# Microbundle cache
59+
.rpt2_cache/
60+
.rts2_cache_cjs/
61+
.rts2_cache_es/
62+
.rts2_cache_umd/
63+
64+
# Optional REPL history
65+
.node_repl_history
66+
67+
# Output of 'npm pack'
68+
*.tgz
69+
70+
# Yarn Integrity file
71+
.yarn-integrity
72+
73+
# dotenv environment variables file
74+
.env
75+
.env.test
76+
77+
# parcel-bundler cache (https://parceljs.org/)
78+
.cache
79+
.parcel-cache
80+
81+
# Next.js build output
82+
.next
83+
out
84+
85+
# Nuxt.js build / generate output
86+
.nuxt
87+
dist
88+
89+
# Gatsby files
90+
.cache/
91+
# Comment in the public line in if your project uses Gatsby and not Next.js
92+
# https://nextjs.org/blog/next-9-1#public-directory-support
93+
# public
94+
95+
# vuepress build output
96+
.vuepress/dist
97+
98+
# Serverless directories
99+
.serverless/
100+
101+
# FuseBox cache
102+
.fusebox/
103+
104+
# DynamoDB Local files
105+
.dynamodb/
106+
107+
# TernJS port file
108+
.tern-port
109+
110+
# Stores VSCode versions used for testing VSCode extensions
111+
.vscode-test
112+
113+
# yarn v2
114+
.yarn/cache
115+
.yarn/unplugged
116+
.yarn/build-state.yml
117+
.yarn/install-state.gz
118+
.pnp.*
119+
120+
121+
### https://raw.github.com/github/gitignore/218a941be92679ce67d0484547e3e142b2f5f6f0/Global/VisualStudioCode.gitignore
122+
123+
.vscode/*
124+
!.vscode/settings.json
125+
!.vscode/tasks.json
126+
!.vscode/launch.json
127+
!.vscode/extensions.json
128+
*.code-workspace
129+
130+
# Local History for Visual Studio Code
131+
.history/
132+
1133
.yalc/
2-
yalc.lock
134+
yalc.lock
135+
lib

package.json

+11-1
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,25 @@
44
"main": "index.js",
55
"author": "Lenz Weber",
66
"license": "MIT",
7+
"bin": {
8+
"generate-rtk": "./lib/bin/cli.js"
9+
},
10+
"scripts": {
11+
"build": "tsc",
12+
"prepare": "npm run build && chmod +x ./lib/bin/cli.js"
13+
},
714
"devDependencies": {
815
"@rtk-incubator/rtk-query": "^0.1.0",
16+
"@types/commander": "^2.12.2",
17+
"@types/lodash": "^4.14.165",
18+
"@types/node": "^14.14.12",
919
"oazapfts": "file:.yalc/oazapfts",
1020
"ts-node": "^9.1.0",
1121
"yalc": "^1.0.0-pre.47"
1222
},
1323
"dependencies": {
1424
"@apidevtools/swagger-parser": "^10.0.2",
15-
"@types/lodash": "^4.14.165",
25+
"commander": "^6.2.0",
1626
"swagger2openapi": "^7.0.4",
1727
"ts-morph": "^9.1.0",
1828
"typescript": "^4.1.2"

src/bin/cli.ts

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#!/usr/bin/env node
2+
3+
import path = require('path')
4+
import program = require('commander')
5+
6+
// tslint:disable-next-line
7+
const meta = require('../../package.json')
8+
import { generateApi, GenerationOptions } from '../generate'
9+
10+
program
11+
.version(meta.version)
12+
.usage('</path/to/some-swagger.yaml>')
13+
.option('--exportName <name>', 'change RTK Query Tree root name')
14+
.option('--reducerPath <path>', 'pass reducer path')
15+
.option('--baseQuery <name>', 'pass baseQuery name')
16+
.option('--argSuffix <name>', 'pass arg suffix')
17+
.option('--responseSuffix <name>', 'pass response suffix')
18+
.option('--baseUrl <url>', 'pass baseUrl')
19+
.parse(process.argv)
20+
21+
if (program.args.length === 0) {
22+
program.help()
23+
} else {
24+
const schemaAbsPath = path.resolve(process.cwd(), program.args[0])
25+
26+
const options = [
27+
'exportName',
28+
'reducerPath',
29+
'baseQuery',
30+
'argSuffix',
31+
'responseSuffix',
32+
'baseUrl'
33+
] as const
34+
35+
const generateApiOptions = options.reduce((s, key) => program[key] ? ({
36+
...s,
37+
[key]: program[key]
38+
}) : s, {} as GenerationOptions);
39+
generateApi(schemaAbsPath, generateApiOptions).then(sourceCode => console.log(sourceCode))
40+
}

src/generate.ts

+14-14
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import { EndpointDefinition } from "./apiModel";
21
import _ from "lodash";
32
import ApiGenerator, {
43
verbs,
@@ -38,10 +37,13 @@ const operationKeys = [
3837
"trace",
3938
] as const;
4039

41-
type GenerationOptions = {
40+
export type GenerationOptions = {
4241
exportName?: string;
4342
reducerPath?: string;
4443
baseQuery?: string;
44+
argSuffix?: string;
45+
responseSuffix?: string;
46+
baseUrl?: string
4547
isDataResponse?(
4648
code: string,
4749
response: OpenAPIV3.ResponseObject,
@@ -58,12 +60,15 @@ function defaultIsDataResponse(
5860
return !Number.isNaN(parsedCode) && parsedCode >= 200 && parsedCode < 300;
5961
}
6062

61-
async function generateApi(
63+
export async function generateApi(
6264
spec: string,
6365
{
6466
exportName = "api",
6567
reducerPath,
6668
baseQuery = "fetchBaseQuery",
69+
argSuffix = "ApiArg",
70+
responseSuffix = "ApiResponse",
71+
baseUrl,
6772
isDataResponse = defaultIsDataResponse,
6873
}: GenerationOptions
6974
) {
@@ -76,6 +81,9 @@ async function generateApi(
7681
const result = await converter.convertObj(doc, {});
7782
v3Doc = result.openapi as OpenAPIV3.Document;
7883
}
84+
if (typeof baseUrl !== 'string') {
85+
baseUrl = v3Doc.servers?.[0].url ?? "https://example.com"
86+
}
7987

8088
const apiGen = new ApiGenerator(v3Doc, {});
8189

@@ -196,10 +204,7 @@ async function generateApi(
196204
[
197205
factory.createPropertyAssignment(
198206
factory.createIdentifier("baseUrl"),
199-
factory.createStringLiteral(
200-
v3Doc.servers?.[0].url ??
201-
"https://example.com"
202-
)
207+
factory.createStringLiteral(baseUrl as string)
203208
),
204209
],
205210
false
@@ -320,7 +325,7 @@ async function generateApi(
320325
undefined,
321326
[factory.createModifier(ts.SyntaxKind.ExportKeyword)],
322327
_.upperFirst(
323-
getOperationName(verb, path, operation.operationId) + "Response"
328+
getOperationName(verb, path, operation.operationId) + responseSuffix
324329
),
325330
undefined,
326331
ResponseType
@@ -380,7 +385,7 @@ async function generateApi(
380385
undefined,
381386
[factory.createModifier(ts.SyntaxKind.ExportKeyword)],
382387
_.upperFirst(
383-
getOperationName(verb, path, operation.operationId) + "QueryArg"
388+
getOperationName(verb, path, operation.operationId) + argSuffix
384389
),
385390
undefined,
386391
factory.createTypeLiteralNode(
@@ -695,8 +700,3 @@ type QueryArgDefinition = {
695700
}
696701
);
697702
type QueryArgDefinitions = Record<string, QueryArgDefinition>;
698-
699-
generateApi(
700-
"/home/weber/tmp/rtk-query-codegen-openapi/test/petstore.json",
701-
{}
702-
).then((result) => console.log(result));

tsconfig.json

+10-8
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@
1010
// "allowJs": true, /* Allow javascript files to be compiled. */
1111
// "checkJs": true, /* Report errors in .js files. */
1212
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
13-
// "declaration": true, /* Generates corresponding '.d.ts' file. */
13+
"declaration": true, /* Generates corresponding '.d.ts' file. */
1414
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
15-
// "sourceMap": true, /* Generates corresponding '.map' file. */
15+
"sourceMap": true, /* Generates corresponding '.map' file. */
1616
// "outFile": "./", /* Concatenate and emit output to single file. */
17-
// "outDir": "./", /* Redirect output structure to the directory. */
18-
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
17+
"outDir": "lib", /* Redirect output structure to the directory. */
18+
"rootDir": "src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
1919
// "composite": true, /* Enable project compilation */
2020
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
2121
// "removeComments": true, /* Do not emit comments to output. */
@@ -35,19 +35,20 @@
3535
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
3636

3737
/* Additional Checks */
38-
// "noUnusedLocals": true, /* Report errors on unused locals. */
38+
"noUnusedLocals": false, /* Report errors on unused locals. */
39+
"resolveJsonModule": true,
3940
// "noUnusedParameters": true, /* Report errors on unused parameters. */
4041
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
4142
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
4243
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
4344

4445
/* Module Resolution Options */
45-
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
46+
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
4647
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
4748
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
4849
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
4950
// "typeRoots": [], /* List of folders to include type definitions from. */
50-
// "types": [], /* Type declaration files to be included in compilation. */
51+
"types": ["node"], /* Type declaration files to be included in compilation. */
5152
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
5253
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
5354
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
@@ -66,5 +67,6 @@
6667
/* Advanced Options */
6768
"skipLibCheck": true /* Skip type checking of declaration files. */,
6869
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
69-
}
70+
},
71+
"exclude": ["test", "lib"]
7072
}

yarn.lock

+17
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,13 @@
141141
multimatch "^5.0.0"
142142
typescript "~4.1.2"
143143

144+
"@types/commander@^2.12.2":
145+
version "2.12.2"
146+
resolved "https://registry.yarnpkg.com/@types/commander/-/commander-2.12.2.tgz#183041a23842d4281478fa5d23c5ca78e6fd08ae"
147+
integrity sha512-0QEFiR8ljcHp9bAbWxecjVRuAMr16ivPiGOw6KFQBVrVd0RQIcM3xKdRisH2EDWgVWujiYtHwhSkSUoAAGzH7Q==
148+
dependencies:
149+
commander "*"
150+
144151
"@types/lodash@^4.14.165":
145152
version "4.14.165"
146153
resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.165.tgz#74d55d947452e2de0742bad65270433b63a8c30f"
@@ -151,6 +158,11 @@
151158
resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.3.tgz#3dca0e3f33b200fc7d1139c0cd96c1268cadfd9d"
152159
integrity sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==
153160

161+
"@types/node@^14.14.12":
162+
version "14.14.12"
163+
resolved "https://registry.yarnpkg.com/@types/node/-/node-14.14.12.tgz#0b1d86f8c40141091285dea02e4940df73bba43f"
164+
integrity sha512-ASH8OPHMNlkdjrEdmoILmzFfsJICvhBsFfAum4aKZ/9U4B6M6tTmTPh+f3ttWdD74CEGV5XvXWkbyfSdXaTd7g==
165+
154166
ajv@^5.5.2:
155167
version "5.5.2"
156168
resolved "https://registry.yarnpkg.com/ajv/-/ajv-5.5.2.tgz#73b5eeca3fab653e3d3f9422b341ad42205dc965"
@@ -329,6 +341,11 @@ color-name@~1.1.4:
329341
resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2"
330342
integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==
331343

344+
commander@*, commander@^6.2.0:
345+
version "6.2.0"
346+
resolved "https://registry.yarnpkg.com/commander/-/commander-6.2.0.tgz#b990bfb8ac030aedc6d11bc04d1488ffef56db75"
347+
integrity sha512-zP4jEKbe8SHzKJYQmq8Y9gYjtO/POJLgIdKgV7B9qNmABVFVc+ctqSX6iXh4mCpJfRBOabiZ2YKPg8ciDw6C+Q==
348+
332349
commander@^2.7.1:
333350
version "2.20.3"
334351
resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33"

0 commit comments

Comments
 (0)