【发布时间】:2021-11-05 07:58:48
【问题描述】:
我正在尝试在 graphQL 控制器中使用 fs.watch() 来观察测试输出 json 文件中的变化,并将测试是否通过他们提出的解决方案返回给用户。
现在,我的突变总是得到null 的答案。
所有测试都运行正常,output.json文件也正确写入,但是控制器函数在返回正确值之前返回null。
我的控制器如下:
import { Context } from "../typescript/types";
import TestModel from "../models/TestModel";
const fs = require("fs-extra");
interface InputSolution {
userId: string;
exerciseId: string;
testIDs: string[];
solution: string;
}
export default class SandboxController {
async postSolution(
parent: any,
args: { input: InputSolution },
context: Context
) {
// 1. delete all files in src and spec, and the output json file
try {
await fs.emptyDir("./userCode/src");
await fs.emptyDir("./userCode/spec");
console.log("success!");
} catch (err) {
console.error(err);
}
// 2. create new files for: the function that is tested, and the tests
const tests = await TestModel.find()
.where("_id")
.in(args.input.testIDs)
.exec();
try {
await fs.writeFile("./userCode/src/solution.js", args.input.solution);
tests.forEach(async (test, index) => {
await fs.writeFile(
`./userCode/spec/test${index}.spec.js`,
test.content
);
});
console.log("success!");
} catch (err) {
console.error(err);
}
// 3. create the flag file to show changes were made
try {
await fs.writeFile(
"./userCode/flag.txt",
args.input.exerciseId + " - " + args.input.userId
);
console.log("success!");
} catch (err) {
console.error(err);
}
// 4. Watch the output file
fs.watch(
"./userCode/flag.txt",
async (eventType: string, filename: string) => {
console.log(`event type is: ${eventType}`);
const json = await fs.readFile(
"./userCode/testLogs/output.json",
"utf8"
);
const output: any = json ? JSON.parse(json) : null;
if (
output &&
(output.numTotalTestSuites > 0 || output.numTotalTests > 0)
) {
//
console.log("numTotalTestSuites", output.numTotalTestSuites);
if (output.numFailedTestSuites === 0 && output.numFailedTests === 0) {
console.log("all good");
return [{ testId: "12", passed: true }];
} else {
console.log("tests failed", output.numFailedTestSuites);
return [{ testId: "12", passed: false }];
}
//
} else {
return [{ testId: "12", passed: false }];
}
}
);
}
}
任何帮助将不胜感激。
【问题讨论】: