-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathgenerator.ts
187 lines (166 loc) · 5.13 KB
/
generator.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/* Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved. */
import { PathLike } from 'fs';
import { join, resolve } from 'path';
import { toPascalCase } from '@sap-cloud-sdk/core';
import { createLogger } from '@sap-cloud-sdk/util';
import execa from 'execa';
import {
existsSync,
mkdirSync,
readdirSync,
readJsonSync,
removeSync,
writeJsonSync
} from 'fs-extra';
import { Project } from 'ts-morph';
import { GeneratorOptions } from './generator-cli';
import { projectOptions, sourceFile } from './utils';
import { toOpenApiServiceMetaData } from './parse-open-api-json';
import { OpenApiServiceMetadata } from './open-api-types';
import { requestBuilderSourceFile } from './request-builder/file';
const logger = createLogger({
level: 'info',
package: 'generator',
messageContext: 'rest-generator'
});
export async function generateRest(options: GeneratorOptions): Promise<void> {
const project = await generateProject(options);
return project.save();
}
export async function generateProject(options: GeneratorOptions) {
if (options.clearOutputDir) {
cleanDirectory(options.outputDir);
}
const files = readdirSync(options.inputDir);
const pathToTemplates = resolve(__dirname, '../templates');
const pathToMustacheValues = join(__dirname, '../mustache-values.json');
const project = new Project(projectOptions());
const openApiServiceMetadata = await Promise.all(
files.map(async file =>
generateOneApi(file, options, pathToTemplates, pathToMustacheValues)
)
);
openApiServiceMetadata.map(metadata =>
generateSourcesForService(metadata, project, options)
);
return project;
}
async function generateOneApi(
inputFileName: string,
options: GeneratorOptions,
pathToTemplates: string,
pathToMustacheValues: string
) {
const dirForService = getDirForService(options.outputDir, inputFileName);
if (!existsSync(dirForService)) {
mkdirSync(dirForService, { recursive: true });
}
const serviceName = getServiceNamePascalCase(inputFileName);
const adjustedOpenApiContent = getAdjustedOpenApiFile(
join(options.inputDir, inputFileName),
serviceName
);
const pathToAdjustedOpenApiDefFile = join(dirForService, 'open-api.json');
writeJsonSync(pathToAdjustedOpenApiDefFile, adjustedOpenApiContent);
await generateFilesUsingOpenAPI(
dirForService,
pathToAdjustedOpenApiDefFile,
pathToTemplates,
pathToMustacheValues
);
return toOpenApiServiceMetaData(
pathToAdjustedOpenApiDefFile,
serviceName,
dirForService
);
}
function generateSourcesForService(
serviceMetadata: OpenApiServiceMetadata,
project: Project,
options: GeneratorOptions
) {
const serviceDir = project.createDirectory(
resolve(options.outputDir.toString(), serviceMetadata.serviceDir)
);
logger.info(`Generating request builder in ${serviceDir}.`);
sourceFile(
serviceDir,
'request-builder',
requestBuilderSourceFile(serviceMetadata),
true
);
}
async function generateFilesUsingOpenAPI(
dirForService: string,
pathToAdjustedOpenApiDefFile: string,
pathToTemplates: string,
pathToMustacheValues: string
) {
const generationArguments = [
'openapi-generator-cli',
'generate',
'-i',
pathToAdjustedOpenApiDefFile,
'-g',
'typescript-axios',
'-o',
resolve(dirForService, 'open-api'),
'-t',
pathToTemplates,
'--api-package',
'api',
'--model-package',
'model',
'--config',
pathToMustacheValues,
'--skip-validate-spec'
];
logger.info(`Argument for openapi generator ${generationArguments}`);
try {
const response = await execa.sync('npx', generationArguments);
if (response !== undefined) {
logger.info(`Generated the client ${response.stdout}`);
}
} catch (err) {
logger.error('In exception block');
logger.error(err);
}
}
function getServiceNamePascalCase(openApiFileName: string) {
const result = getServiceNameWithoutExtensions(openApiFileName);
return toPascalCase(result);
}
function getServiceNameWithoutExtensions(openApiFileName: string): string {
let fileNameWithoutExtension = openApiFileName.replace('.json', '');
fileNameWithoutExtension = fileNameWithoutExtension.replace('-openapi', '');
return fileNameWithoutExtension;
}
function getDirForService(outputDir: PathLike, inputFileName: string) {
const withoutExtension = getServiceNameWithoutExtensions(inputFileName);
return join(outputDir as string, withoutExtension);
}
function getAdjustedOpenApiFile(filePath: string, tag: string): JSON {
const contentInitial = readJsonSync(filePath);
const contentAdjusted = addTagToService(tag, contentInitial);
return contentAdjusted;
}
function cleanDirectory(path: PathLike) {
if (existsSync(path)) {
removeSync(path.toString());
}
mkdirSync(path);
}
function addTagToService(tag: string, fileContent: JSON): JSON {
const copy = { ...fileContent };
copy['tags'] = [{ name: tag }];
const paths = copy['paths'];
Object.keys(paths).forEach(path => {
Object.keys(paths[path]).forEach(method => {
paths[path][method]['tags'] = [
...(paths[path][method]['tags'] || []),
tag
];
});
});
return copy;
}