oav/lib/xMsExampleExtractor.ts

315 строки
11 KiB
TypeScript
Исходник Обычный вид История

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
2020-11-24 06:07:36 +03:00
import * as fs from "fs";
import * as pathlib from "path";
import { MutableStringMap, StringMap, entries, mapEntries, keys, values } from "@azure-tools/openapi-tools-common";
import swaggerParser from "swagger-parser";
import { log } from "./util/logging";
interface Options {
2020-11-24 06:07:36 +03:00
output?: string;
shouldResolveXmsExamples?: unknown;
matchApiVersion?: unknown;
}
const mkdirRecursiveSync = (dir: string) => {
if (!fs.existsSync(dir)) {
2020-11-24 06:07:36 +03:00
const parent = pathlib.dirname(dir);
if (parent !== dir) {
2020-11-24 06:07:36 +03:00
mkdirRecursiveSync(parent);
}
2020-11-24 06:07:36 +03:00
fs.mkdirSync(dir);
}
2020-11-24 06:07:36 +03:00
};
/**
* @class
*/
2018-05-30 06:30:11 +03:00
export class XMsExampleExtractor {
2020-11-24 06:07:36 +03:00
private readonly specPath: string;
private readonly recordings: string;
private readonly options: Options;
/**
* @constructor
* Initializes a new instance of the xMsExampleExtractor class.
2018-01-27 03:54:11 +03:00
*
* @param {string} specPath the swagger spec path
2018-01-27 03:54:11 +03:00
*
* @param {object} recordings the folder for recordings
2018-01-27 03:54:11 +03:00
*
* @param {object} [options] The options object
2018-01-27 03:54:11 +03:00
*
2018-06-04 16:16:47 +03:00
* @param {object} [options.matchApiVersion] Only generate examples if api-version matches.
* Default: false
2018-01-27 03:54:11 +03:00
*
* @param {object} [options.output] Output folder for the generated examples.
*/
public constructor(specPath: string, recordings: string, options: Options) {
if (
specPath === null ||
specPath === undefined ||
typeof specPath.valueOf() !== "string" ||
!specPath.trim().length
) {
2018-06-04 16:16:47 +03:00
throw new Error(
"specPath is a required property of type string and it cannot be an empty string."
2020-11-24 06:07:36 +03:00
);
}
if (
recordings === null ||
recordings === undefined ||
typeof recordings.valueOf() !== "string" ||
!recordings.trim().length
) {
2018-06-04 16:16:47 +03:00
throw new Error(
"recordings is a required property of type string and it cannot be an empty string."
2020-11-24 06:07:36 +03:00
);
}
2020-11-24 06:07:36 +03:00
this.specPath = specPath;
this.recordings = recordings;
if (!options) {
2020-11-24 06:07:36 +03:00
options = {};
}
if (options.output === null || options.output === undefined) {
2020-11-24 06:07:36 +03:00
options.output = process.cwd() + "/output";
}
if (
options.shouldResolveXmsExamples === null ||
options.shouldResolveXmsExamples === undefined
) {
2020-11-24 06:07:36 +03:00
options.shouldResolveXmsExamples = true;
}
if (options.matchApiVersion === null || options.matchApiVersion === undefined) {
2020-11-24 06:07:36 +03:00
options.matchApiVersion = false;
}
2020-11-24 06:07:36 +03:00
this.options = options;
log.debug(`specPath : ${this.specPath}`);
log.debug(`recordings : ${this.recordings}`);
log.debug(`options.output : ${this.options.output}`);
log.debug(`options.matchApiVersion : ${this.options.matchApiVersion}`);
}
public extractOne(
relativeExamplesPath: string,
outputExamples: string,
2020-11-24 06:07:36 +03:00
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
api: any,
recordingFileName: string
2020-11-24 06:07:36 +03:00
): void {
const recording = JSON.parse(fs.readFileSync(recordingFileName).toString());
const paths = api.paths;
let pathIndex = 0;
let pathParams: MutableStringMap<number> = {};
for (const path of keys(paths)) {
2020-11-24 06:07:36 +03:00
pathIndex++;
const searchResult = path.match(/\/{\w*\}/g);
const pathParts = path.split("/");
let pathToMatch = path;
pathParams = {};
if (searchResult !== null) {
for (const match of searchResult) {
2020-11-24 06:07:36 +03:00
const splitRegEx = /[{}]/;
const pathParam = match.split(splitRegEx)[1];
2020-11-24 06:07:36 +03:00
for (const [part, value] of entries(pathParts)) {
const pathPart = "/" + value;
if (pathPart.localeCompare(match) === 0) {
2020-11-24 06:07:36 +03:00
pathParams[pathParam] = part;
}
}
2020-11-24 06:07:36 +03:00
pathToMatch = pathToMatch.replace(match, "/[^/]+");
}
}
2020-11-24 06:07:36 +03:00
let newPathToMatch = pathToMatch.replace(/\//g, "\\/");
newPathToMatch = newPathToMatch + "$";
// for this API path (and method), try to find it in the recording file, and get
// the data
2020-11-24 06:07:36 +03:00
const recordingEntries: StringMap<any> = recording.Entries;
let entryIndex = 0;
const queryParams: MutableStringMap<unknown> = {};
for (const recordingEntry of values(recordingEntries)) {
2020-11-24 06:07:36 +03:00
entryIndex++;
let recordingPath = JSON.stringify(recordingEntry.RequestUri);
const recordingPathQueryParams = recordingPath.split("?")[1].slice(0, -1);
const queryParamsArray = recordingPathQueryParams.split("&");
for (const value of queryParamsArray) {
2020-11-24 06:07:36 +03:00
const queryParam = value.split("=");
queryParams[queryParam[0]] = queryParam[1];
}
2020-11-24 06:07:36 +03:00
const headerParams = recordingEntry.RequestHeaders;
// if command-line included check for API version, validate api-version from URI in
// recordings matches the api-version of the spec
if (
!this.options.matchApiVersion ||
("api-version" in queryParams && queryParams["api-version"] === api.info.version)
) {
2020-11-24 06:07:36 +03:00
recordingPath = recordingPath.replace(/\?.*/, "");
const recordingPathParts = recordingPath.split("/");
// eslint-disable-next-line @typescript-eslint/prefer-regexp-exec
const match = recordingPath.match(newPathToMatch);
if (match !== null) {
2020-11-24 06:07:36 +03:00
log.silly("path: " + path);
log.silly("recording path: " + recordingPath);
2020-11-24 06:07:36 +03:00
const pathParamsValues: MutableStringMap<unknown> = {};
for (const [p, v] of mapEntries(pathParams)) {
const index = v;
pathParamsValues[p] = recordingPathParts[index];
}
// found a match in the recording
2020-11-24 06:07:36 +03:00
const requestMethodFromRecording = recordingEntry.RequestMethod;
const infoFromOperation = paths[path][requestMethodFromRecording.toLowerCase()];
if (typeof infoFromOperation !== "undefined") {
// need to consider each method in operation
2020-11-24 06:07:36 +03:00
const fileNameArray = recordingFileName.split("/");
let fileName = fileNameArray[fileNameArray.length - 1];
fileName = fileName.split(".json")[0];
fileName = fileName.replace(/\//g, "-");
const exampleFileName = `${fileName}-${requestMethodFromRecording}-example-${pathIndex}${entryIndex}.json`;
const ref = {
2020-11-24 06:07:36 +03:00
$ref: relativeExamplesPath + exampleFileName,
};
const exampleFriendlyName = `${fileName}${requestMethodFromRecording}${pathIndex}${entryIndex}`;
log.debug(`exampleFriendlyName: ${exampleFriendlyName}`);
if (!("x-ms-examples" in infoFromOperation)) {
2020-11-24 06:07:36 +03:00
infoFromOperation["x-ms-examples"] = {};
}
2020-11-24 06:07:36 +03:00
infoFromOperation["x-ms-examples"][exampleFriendlyName] = ref;
const exampleL: {
2020-11-24 06:07:36 +03:00
parameters: MutableStringMap<unknown>;
responses: MutableStringMap<{
2020-11-24 06:07:36 +03:00
body?: unknown;
}>;
} = {
parameters: {},
2020-11-24 06:07:36 +03:00
responses: {},
};
const paramsToProcess = [
2020-11-24 06:07:36 +03:00
...mapEntries(pathParamsValues),
...mapEntries(queryParams),
...mapEntries(headerParams),
];
for (const paramEntry of paramsToProcess) {
2020-11-24 06:07:36 +03:00
const param = paramEntry[0];
const v = paramEntry[1];
exampleL.parameters[param] = v;
}
2020-11-24 06:07:36 +03:00
const params = infoFromOperation.parameters;
for (const param of keys(infoFromOperation.parameters)) {
if (params[param].in === "body") {
2020-11-24 06:07:36 +03:00
const bodyParamName = params[param].name;
const bodyParamValue = recordingEntry.RequestBody;
const bodyParamExample: MutableStringMap<unknown> = {};
bodyParamExample[bodyParamName] = bodyParamValue;
exampleL.parameters[bodyParamName] =
2020-11-24 06:07:36 +03:00
bodyParamValue !== "" ? JSON.parse(bodyParamValue) : "";
}
}
2020-11-24 06:07:36 +03:00
for (const _v of keys(infoFromOperation.responses)) {
const statusCodeFromRecording = recordingEntry.StatusCode;
const responseBody = recordingEntry.ResponseBody;
exampleL.responses[statusCodeFromRecording] = {
2020-11-24 06:07:36 +03:00
body: responseBody !== "" ? JSON.parse(responseBody) : "",
};
}
2020-11-24 06:07:36 +03:00
log.info(`Writing x-ms-examples at ${outputExamples + exampleFileName}`);
const examplePath = pathlib.join(outputExamples, exampleFileName);
const dir = pathlib.dirname(examplePath);
mkdirRecursiveSync(dir);
fs.writeFileSync(examplePath, JSON.stringify(exampleL, null, 2));
}
}
}
}
}
}
/**
* Extracts x-ms-examples from the recordings
*/
public async extract(): Promise<StringMap<unknown>> {
if (this.options.output === undefined) {
2020-11-24 06:07:36 +03:00
throw new Error("this.options.output === undefined");
}
2020-11-24 06:07:36 +03:00
this.mkdirSync(this.options.output);
this.mkdirSync(this.options.output + "/examples");
this.mkdirSync(this.options.output + "/swagger");
2020-11-24 06:07:36 +03:00
const outputExamples = pathlib.join(this.options.output, "examples");
const relativeExamplesPath = "../examples/";
const specName = this.specPath.split("/");
const outputSwagger = pathlib.join(
this.options.output,
"swagger",
specName[specName.length - 1].split(".")[0] + ".json"
2020-11-24 06:07:36 +03:00
);
2020-11-24 06:07:36 +03:00
const accErrors: MutableStringMap<unknown> = {};
const filesArray: string[] = [];
this.getFileList(this.recordings, filesArray);
2020-11-24 06:07:36 +03:00
const recordingFiles = filesArray;
2018-06-04 16:16:47 +03:00
try {
2020-11-24 06:07:36 +03:00
const api = await swaggerParser.parse(this.specPath);
for (const recordingFileName of recordingFiles) {
2020-11-24 06:07:36 +03:00
log.debug(`Processing recording file: ${recordingFileName}`);
try {
2020-11-24 06:07:36 +03:00
this.extractOne(relativeExamplesPath, outputExamples, api, recordingFileName);
log.info(`Writing updated swagger with x-ms-examples at ${outputSwagger}`);
fs.writeFileSync(outputSwagger, JSON.stringify(api, null, 2));
2018-06-04 16:16:47 +03:00
} catch (err) {
2020-11-24 06:07:36 +03:00
accErrors[recordingFileName] = err.toString();
log.warn(`Error processing recording file: "${recordingFileName}"`);
log.warn(`Error: "${err.toString()} "`);
}
}
2018-06-04 16:16:47 +03:00
if (JSON.stringify(accErrors) !== "{}") {
2020-11-24 06:07:36 +03:00
log.error(`Errors loading/parsing recording files.`);
log.error(`${JSON.stringify(accErrors)}`);
}
2018-06-04 16:16:47 +03:00
} catch (err) {
2020-11-24 06:07:36 +03:00
process.exitCode = 1;
log.error(err);
2018-06-04 16:16:47 +03:00
}
2020-11-24 06:07:36 +03:00
return accErrors;
}
private mkdirSync(dir: string): void {
try {
2020-11-24 06:07:36 +03:00
fs.mkdirSync(dir);
} catch (e) {
if (e.code !== "EEXIST") {
2020-11-24 06:07:36 +03:00
throw e;
}
}
}
2018-06-09 02:35:55 +03:00
private getFileList(dir: string, fileList: string[]): string[] {
2020-11-24 06:07:36 +03:00
const files = fs.readdirSync(dir);
fileList = fileList || [];
files.forEach((file) => {
if (fs.statSync(pathlib.join(dir, file)).isDirectory()) {
2020-11-24 06:07:36 +03:00
fileList = this.getFileList(pathlib.join(dir, file), fileList);
2018-06-04 16:16:47 +03:00
} else {
2020-11-24 06:07:36 +03:00
fileList.push(pathlib.join(dir, file));
}
2020-11-24 06:07:36 +03:00
});
return fileList;
}
}