Skip to content

Commit 6d279fb

Browse files
committed
clean: rm tmp file and get original file back
1 parent 54f7f35 commit 6d279fb

File tree

4 files changed

+45
-43
lines changed

4 files changed

+45
-43
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
"scripts": {
1010
"lint": "eslint .",
1111
"lint-fix": "eslint . --fix",
12-
"test": "env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha -r ts-node/register '**/*.test.*'",
12+
"test": "env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha -r ts-node/register 'test/*.test.*'",
1313
"prebuild": "rimraf lib",
1414
"build": "tsc --build",
1515
"prepublishOnly": "npm run build"

src/APICollector.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,7 @@ export default class APICollector implements APICollectorInterface {
267267
if (!url) throw new Error('No url found');
268268
const method = this.extractMethod(serverResponse);
269269
const operationObj: OpenAPIV3_1.OperationObject = {};
270-
const methodsHasReqBody = ['post', 'put']
270+
const methodsHasReqBody = ['post', 'put'];
271271

272272
if (statusCode < 400) {
273273
const headers = this.extractHeaders(serverResponse);

src/APIGenerator.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,19 +41,19 @@ export default class APIGenerator {
4141
const output = opts.output || 'api.yaml';
4242
const fileFormat = path.extname(output);
4343
if (!SUPPORTED_FORMAT.includes(fileFormat)) {
44-
throw new Error(`${fileFormat} file not supported`)
44+
throw new Error(`${fileFormat} file not supported`);
4545
}
4646

4747
await mkdir(path.dirname(output), { recursive: true });
4848
switch (fileFormat) {
4949
case ".json": {
5050
await writeFile(output, JSON.stringify(apiDoc, null, 2));
51-
break
51+
break;
5252
}
5353
case ".yaml": {
54-
const yamlData = YAML.stringify(apiDoc)
54+
const yamlData = YAML.stringify(apiDoc);
5555
await writeFile(output, yamlData);
56-
break
56+
break;
5757
}
5858
}
5959
}

src/index.ts

Lines changed: 39 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import { spawn } from 'child_process';
22
import fsPromises from 'fs/promises';
3-
import { existsSync } from 'fs'
3+
import { existsSync } from 'fs';
44

55
import {
66
PREFIX_RESPONSE_BODY_DATA,
77
PREFIX_SERVER_RESPONSE
8-
} from './constants'
8+
} from './constants';
99
import RequestHook from './RequestHook';
1010
import APICollector from './APICollector';
1111
import APIGenerator from './APIGenerator';
@@ -27,69 +27,65 @@ export async function runner (
2727
}
2828

2929
const projectCWD = process.cwd();
30-
const packageJSONStr = await fsPromises.readFile(projectCWD + '/package.json', 'utf8')
31-
const packageJSON = JSON.parse(packageJSONStr)
32-
const mainFilePath = packageJSON?.outdoc?.main || packageJSON?.main
33-
if (!mainFilePath) throw new Error('Please define main or outdoc.main in package.json')
30+
const packageJSONStr = await fsPromises.readFile(projectCWD + '/package.json', 'utf8');
31+
const packageJSON = JSON.parse(packageJSONStr);
32+
const mainFilePath = packageJSON?.outdoc?.main || packageJSON?.main;
33+
if (!mainFilePath) throw new Error('Please define main or outdoc.main in package.json');
3434

35-
const mainFileAbsolutePath = `${projectCWD}/${mainFilePath}`
35+
const mainFileAbsolutePath = projectCWD + "/" + mainFilePath;
36+
const tmpFileAbsoluteath = projectCWD + "/outdoc_tmp_file";
3637
const apiCollector = new APICollector();
3738
const requestHook = new RequestHook(apiCollector);
3839

39-
const injectedCodes = RequestHook.getInjectedCodes()
40-
await fsPromises.copyFile(mainFileAbsolutePath, projectCWD + "/outdoc_tmp_file")
41-
await fsPromises.writeFile(mainFileAbsolutePath, injectedCodes, { flag: "a" })
42-
await fsPromises.appendFile(mainFileAbsolutePath, "// @ts-nocheck")
40+
const injectedCodes = RequestHook.getInjectedCodes();
41+
await fsPromises.copyFile(mainFileAbsolutePath, projectCWD + "/outdoc_tmp_file");
42+
await fsPromises.writeFile(mainFileAbsolutePath, injectedCodes, { flag: "a" });
43+
await fsPromises.appendFile(mainFileAbsolutePath, "// @ts-nocheck");
4344

4445
const childProcess = spawn(args[0], args.slice(1), {
4546
detached: true,
4647
stdio: ["inherit", "pipe", "inherit"]
4748
});
4849

4950
childProcess.stdout.on('data', (data) => {
50-
const dataStr = data.toString()
51+
const dataStr = data.toString();
5152

5253
if (dataStr.startsWith(PREFIX_RESPONSE_BODY_DATA)) {
5354
try {
54-
const res = JSON.parse(dataStr.substr(PREFIX_RESPONSE_BODY_DATA.length))
55+
const res = JSON.parse(dataStr.substr(PREFIX_RESPONSE_BODY_DATA.length));
5556
if (res.data?.encoding === 'buffer') {
56-
res.data.chunk = new Buffer(res.data.chunk)
57+
res.data.chunk = new Buffer(res.data.chunk);
5758
}
58-
requestHook.handleResponseBodyData(res)
59+
requestHook.handleResponseBodyData(res);
5960
} catch (err) {
6061
if (err instanceof Error) {
61-
process.stderr.write(err.message)
62+
process.stderr.write(err.message);
6263
}
6364
}
64-
return
65+
return;
6566
}
6667

6768
if (dataStr.startsWith(PREFIX_SERVER_RESPONSE)) {
6869
try {
69-
const res = JSON.parse(dataStr.substr(PREFIX_SERVER_RESPONSE.length))
70+
const res = JSON.parse(dataStr.substr(PREFIX_SERVER_RESPONSE.length));
7071
if (res.data?.req?._readableState) {
71-
const headData = res.data.req._readableState.buffer.head.data
72-
res.data.req._readableState.buffer.head.data = new Buffer(headData)
72+
const headData = res.data.req._readableState.buffer.head.data;
73+
res.data.req._readableState.buffer.head.data = new Buffer(headData);
7374
}
74-
requestHook.handleServerResponse(res)
75+
requestHook.handleServerResponse(res);
7576
} catch (err) {
7677
if (err instanceof Error) {
77-
process.stderr.write(err.message)
78+
process.stderr.write(err.message);
7879
}
7980
}
80-
return
81+
return;
8182
}
8283

83-
process.stdout.write(data.toString())
84-
})
84+
process.stdout.write(data.toString());
85+
});
8586

8687
childProcess.on('close', async (code) => {
87-
const tmpFilePath = projectCWD + "/outdoc_tmp_file"
88-
if (existsSync(tmpFilePath)) {
89-
await fsPromises.copyFile(projectCWD + "/outdoc_tmp_file", mainFileAbsolutePath)
90-
await fsPromises.rm(projectCWD + "/outdoc_tmp_file")
91-
}
92-
88+
await rmTmpFileAndGetOriginalBack(tmpFileAbsoluteath, mainFileAbsolutePath);
9389
if (code === 0) {
9490
try {
9591
await APIGenerator.generate(
@@ -111,10 +107,16 @@ export async function runner (
111107
});
112108

113109
process.on('SIGINT', async () => {
114-
const tmpFilePath = projectCWD + "/outdoc_tmp_file"
115-
if (existsSync(tmpFilePath)) {
116-
await fsPromises.copyFile(tmpFilePath, mainFileAbsolutePath)
117-
await fsPromises.rm(tmpFilePath)
118-
}
119-
});
110+
await rmTmpFileAndGetOriginalBack(tmpFileAbsoluteath, mainFileAbsolutePath);
111+
});
120112
}
113+
114+
const rmTmpFileAndGetOriginalBack = async (
115+
tmpFilePath: string,
116+
mainFilePath: string
117+
) => {
118+
if (existsSync(tmpFilePath)) {
119+
await fsPromises.copyFile(tmpFilePath, mainFilePath);
120+
await fsPromises.rm(tmpFilePath);
121+
}
122+
};

0 commit comments

Comments
 (0)