Skip to content

Commit 4a844e3

Browse files
authored
Revert "feat: implement --include-tag"
1 parent 1d7feba commit 4a844e3

5 files changed

Lines changed: 24 additions & 171 deletions

File tree

src/config.ts

Lines changed: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import { Oas3Operation, Oas3Schema, Referenced } from "@redocly/openapi-core/lib/typings/openapi"
1+
import { Oas3Definition } from "@redocly/openapi-core"
2+
import { Oas3Operation } from "@redocly/openapi-core/lib/typings/openapi"
23
import { cli } from "cleye"
34
import { name, version } from "../package.json"
4-
import { PathItem } from "./schema"
55

66
export type OpConfig = Oas3Operation & { method: string; path: string }
77
export type OpName = [string, string]
@@ -10,28 +10,20 @@ export type Config = {
1010
source: string
1111
output: string | null
1212
name: string
13-
includeTags: string[] | null
1413
parseDates: boolean
1514
inlineEnums: boolean
1615
resolveName?: (ctx: Context, op: OpConfig, proposal: OpName) => OpName | undefined
1716
headers: Record<string, string>
1817
}
1918

20-
export type Context = Config & {
21-
paths: Record<string, PathItem>
22-
schemas: Record<string, Referenced<Oas3Schema>>
23-
logTag: string
24-
usedNames: Set<string>
25-
}
19+
export type Context = Config & { doc: Oas3Definition; logTag: string; usedNames: Set<string> }
2620

2721
export const initCtx = (config?: Partial<Context>): Context => {
2822
return {
2923
source: "",
3024
output: "",
3125
name: "ApiClient",
32-
paths: {},
33-
schemas: {},
34-
includeTags: null,
26+
doc: { openapi: "3.1.0" },
3527
parseDates: false,
3628
inlineEnums: false,
3729
headers: {},
@@ -62,11 +54,6 @@ export const getCliConfig = () => {
6254
description: "API class name to export",
6355
default: "ApiClient",
6456
},
65-
includeTag: {
66-
type: [String],
67-
description: "Only include operations with the given tags.",
68-
default: null,
69-
},
7057
parseDates: {
7158
type: Boolean,
7259
description: "Parse dates as Date objects",
@@ -91,7 +78,6 @@ export const getCliConfig = () => {
9178
source: argv._.source,
9279
output: argv._.output ?? null,
9380
name: argv.flags.name,
94-
includeTags: argv.flags.includeTag,
9581
parseDates: argv.flags.parseDates,
9682
inlineEnums: argv.flags.inlineEnums,
9783
headers: parseHeaders(argv.flags.header),

src/generator.ts

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
import redocly, { BaseResolver, Oas3Definition } from "@redocly/openapi-core"
22
import { filterEmpty, filterNullable } from "array-utils-ts"
3-
import { lowerFirst, sortBy, uniqBy, upperFirst } from "lodash-es"
3+
import { isObject, lowerFirst, sortBy, uniqBy, upperFirst } from "lodash-es"
44
import { convertObj } from "swagger2openapi"
55
import ts from "typescript"
66
import { Context, OpConfig, OpName } from "./config"
77
import { getRepSchema, getReqSchema, unref } from "./schema"
88
import { makeType, makeTypeAlias, normalizeIdentifier } from "./type-gen"
99

1010
const f = ts.factory
11+
const HttpMethods = ["get", "post", "put", "patch", "delete", "head", "options", "trace"] as const
1112

1213
const normalizeOpName = (val: string) => {
1314
const articles = new Set(["a", "an", "the"])
@@ -163,10 +164,21 @@ const prepareNs = (ctx: Context, name: string, handlers: ts.PropertyAssignment[]
163164
const prepareRoutes = async (ctx: Context) => {
164165
const routes: Record<string, ts.PropertyAssignment[]> = {}
165166

166-
for (const [path, pathConfig] of Object.entries(ctx.paths)) {
167-
for (const [method, config] of Object.entries(pathConfig.ops)) {
167+
for (const [path, pathConfig] of Object.entries(ctx.doc.paths ?? {})) {
168+
ctx.logTag = `${"[ALL]".toUpperCase().padEnd(6, " ")} ${path}`
169+
if (!isObject(pathConfig)) continue
170+
171+
if ("$ref" in pathConfig) {
172+
console.warn(`${ctx.logTag} $ref should be resolved before (skipping)`)
173+
continue
174+
}
175+
176+
for (const method of HttpMethods) {
168177
ctx.logTag = `${method.toUpperCase().padEnd(6, " ")} ${path}`
169178

179+
const config = pathConfig[method]
180+
if (!config) continue
181+
170182
if (pathConfig.parameters) {
171183
config.parameters = [...(config.parameters ?? []), ...pathConfig.parameters]
172184
}
@@ -196,7 +208,7 @@ const prepareRoutes = async (ctx: Context) => {
196208

197209
const prepareTypes = async (ctx: Context) => {
198210
const types: ts.DeclarationStatement[] = []
199-
const typesConfig = sortBy(Object.entries(ctx.schemas), ([k]) => k)
211+
const typesConfig = sortBy(Object.entries(ctx.doc.components?.schemas ?? {}), ([k]) => k)
200212
for (const [name, config] of typesConfig) {
201213
try {
202214
types.push(makeTypeAlias(ctx, name, config))

src/main.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,10 @@ import { fileURLToPath } from "url"
55
import { Config, initCtx } from "./config"
66
import { generateAst, loadSchema } from "./generator"
77
import { formatCode, printCode } from "./printer"
8-
import { filterSchema } from "./schema"
98

109
export const apigen = async (config: Partial<Config> & Pick<Config, "source" | "output">) => {
1110
const doc = await loadSchema({ url: config.source, headers: config.headers })
12-
const { paths, schemas } = filterSchema(doc, config)
13-
const ctx = initCtx({ ...config, paths, schemas })
11+
const ctx = initCtx({ ...config, doc })
1412
const { modules, types } = await generateAst(ctx)
1513

1614
const filepath = join(dirname(fileURLToPath(import.meta.url)), "_template.ts")

src/schema.ts

Lines changed: 3 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -1,77 +1,16 @@
11
import {
22
Oas3_1Schema,
3-
Oas3Definition,
43
Oas3Operation,
54
Oas3Parameter,
65
Oas3RequestBody,
76
Oas3Schema,
87
Referenced,
98
} from "@redocly/openapi-core/lib/typings/openapi"
10-
import { get, isObject } from "lodash-es"
11-
import { Config, Context } from "./config"
9+
import { get } from "lodash-es"
10+
import { Context } from "./config"
1211

1312
export type OAS3 = Oas3Schema | Oas3_1Schema
1413

15-
const HttpMethods = ["get", "post", "put", "patch", "delete", "head", "options", "trace"] as const
16-
17-
// Oas3PathItem defines each method operation as a property.
18-
// We want to be able to iterate over methods so we introduce this type.
19-
export interface PathItem {
20-
ops: Record<string, Oas3Operation>
21-
summary?: string
22-
description?: string
23-
parameters?: Array<Referenced<Oas3Parameter>>
24-
}
25-
26-
export function filterSchema(doc: Oas3Definition, config: Partial<Config>) {
27-
const paths: Record<string, PathItem> = {}
28-
let usedSchemaRefs = new Set<string>()
29-
for (const [path, pathConfig] of Object.entries(doc.paths ?? {})) {
30-
const logTag = `${"[ALL]".toUpperCase().padEnd(6, " ")} ${path}`
31-
if (!isObject(pathConfig)) continue
32-
33-
if ("$ref" in pathConfig) {
34-
console.warn(`${logTag} $ref should be resolved before (skipping)`)
35-
continue
36-
}
37-
38-
paths[path] = {
39-
ops: {},
40-
summary: pathConfig.summary,
41-
description: pathConfig.description,
42-
parameters: pathConfig.parameters,
43-
}
44-
45-
for (const method of HttpMethods) {
46-
const op = pathConfig[method]
47-
if (!op) continue
48-
49-
if (config.includeTags && !op.tags?.some((tag) => config.includeTags!.includes(tag))) {
50-
continue
51-
}
52-
53-
paths[path].ops[method] = op
54-
extractSchemaReferences(op, usedSchemaRefs)
55-
}
56-
}
57-
const schemas = doc.components?.schemas ?? {}
58-
59-
// When we filter out operations we also want to filter out schemas that are no longer used.
60-
let schemaRefsToCheck = usedSchemaRefs
61-
while (schemaRefsToCheck.size > 0) {
62-
const newSchemaRefs = new Set<string>()
63-
for (const ref of schemaRefsToCheck) {
64-
extractSchemaReferences(schemas[ref], newSchemaRefs)
65-
}
66-
schemaRefsToCheck = newSchemaRefs.difference(usedSchemaRefs)
67-
usedSchemaRefs = usedSchemaRefs.union(newSchemaRefs)
68-
}
69-
for (const unusedSchema of new Set(Object.keys(schemas)).difference(usedSchemaRefs)) {
70-
delete schemas[unusedSchema]
71-
}
72-
return { paths, schemas }
73-
}
74-
7514
// todo: wrong <T> typing
7615
export const unref = <T extends Oas3RequestBody | Oas3Parameter | OAS3>(
7716
ctx: Context,
@@ -84,7 +23,7 @@ export const unref = <T extends Oas3RequestBody | Oas3Parameter | OAS3>(
8423
const obj = parts.reduce(
8524
// openapi encodes "/" in key as "~1"
8625
(acc, x) => get(acc, x, get(acc, decodeURIComponent(x).replaceAll("~1", "/"))),
87-
{ components: { schemas: ctx.schemas } },
26+
ctx.doc,
8827
)
8928

9029
if (obj) return obj as unknown as T
@@ -147,23 +86,3 @@ export const getRepSchema = (ctx: Context, config: Oas3Operation): OAS3 | undefi
14786

14887
return undefined
14988
}
150-
151-
function extractSchemaReferences(obj: any, schemaRefs: Set<string>): void {
152-
if (obj === null || obj === undefined) {
153-
return
154-
}
155-
156-
if (typeof obj === "object" && !Array.isArray(obj) && obj.$ref) {
157-
const ref = obj.$ref
158-
if (typeof ref === "string" && ref.startsWith("#/components/schemas/")) {
159-
const schemaName = ref.replace("#/components/schemas/", "")
160-
schemaRefs.add(schemaName)
161-
}
162-
}
163-
164-
if (Array.isArray(obj)) {
165-
obj.forEach((item) => extractSchemaReferences(item, schemaRefs))
166-
} else if (typeof obj === "object") {
167-
Object.values(obj).forEach((prop) => extractSchemaReferences(prop, schemaRefs))
168-
}
169-
}

test/schema.test.ts

Lines changed: 0 additions & 62 deletions
This file was deleted.

0 commit comments

Comments
 (0)