-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
cli.ts
85 lines (74 loc) · 2.44 KB
/
cli.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Usage: npx tsx cli.ts or pnpm run generate:swagger
import { cli } from "cleye";
import swaggerJsdoc, { type OAS3Definition, type Options } from "swagger-jsdoc";
import { writeFileSync } from "node:fs";
import { join } from "node:path";
type SwaggerOptions = Options & {
apiFolder?: string;
schemaFolders?: string[];
definition: OAS3Definition;
outputFile?: string;
};
// Parse argv
const argv = cli({
name: "apidoc-cli",
parameters: [
"[title]", // Title is optional
"[description]", // Description is optional
],
// Define flags/options
// Becomes available in .flags
flags: {
// Parses `--output` as a string
output: {
type: String,
description: "Output file path",
default: "public/docs/open-api.json",
},
},
});
const defaultSwaggerOptions: SwaggerOptions = {
definition: {
openapi: "3.0.0",
info: {
title: argv._.title ?? "API Documentation",
description: argv._.description ?? "Your awesome API Documentation generated by CLI.",
termsOfService: "https://productsway.com/terms",
version: "1.0",
contact: {
name: "Dung Huynh Duc",
email: "[email protected]",
url: "https://productsway.com",
},
},
},
};
function createSwaggerSpec({
apiFolder = "services",
schemaFolders = [],
...swaggerOptions
}: SwaggerOptions) {
const scanFolders = [apiFolder, ...schemaFolders];
const apis = scanFolders.flatMap((folder) => {
const apiDirectory = join(process.cwd(), folder);
const publicDirectory = join(process.cwd(), "public");
const fileTypes = ["ts", "tsx", "jsx", "js", "json", "swagger.yaml"];
return [
...fileTypes.map((fileType) => `${apiDirectory}/**/*.${fileType}`),
// Support load static files from public directory
...["swagger.yaml", "json"].map((fileType) => `${publicDirectory}/**/*.${fileType}`),
];
});
const options = {
...swaggerOptions,
apis, // Files containing annotations for swagger/openapi
};
const spec = swaggerJsdoc(options);
return spec;
}
const spec = createSwaggerSpec({
...defaultSwaggerOptions,
apiFolder: "services",
});
writeFileSync(argv.flags.output, JSON.stringify(spec, null, 2));
console.log(`Swagger spec written to ${argv.flags.output}`);