-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmocks.mjs
More file actions
106 lines (91 loc) · 2.73 KB
/
mocks.mjs
File metadata and controls
106 lines (91 loc) · 2.73 KB
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
import bodyParser from "body-parser";
import { getTask, startTask } from "./mock-task.mjs";
/** @typedef {import("express").RequestHandler} RequestHandler */
/** @type {RequestHandler} */
const sendTask = (req, res) => {
const task = startTask(req.body.input);
res.send(task);
};
const getTaskDetail = async (req, res, taskId) => {
// await new Promise((resolve) => setTimeout(resolve, 1000));
const task = getTask(taskId);
if (!task) {
res.status(404).send({ error: "Task not found" });
return;
}
let sent = false;
task.subscribe(({ done, value }) => {
if (!sent) {
res.status(200);
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.flushHeaders();
sent = true;
}
if (value) {
res.write(`data: ${JSON.stringify(value)}\n\n`);
// `flush` is added by [compression](https://www.npmjs.com/package/compression)
res.flush?.();
}
if (done) {
res.write("data: [DONE]\n\n");
res.end();
}
});
};
const humanInput = (req, res, taskId, jobId) => {
const task = getTask(taskId);
if (!task) {
res.status(404).send({ error: "Task not found" });
return;
}
try {
task.humanInput(jobId, req.body.input);
res.status(200).send({ message: "ok" });
} catch (e) {
res.status(400).send({ error: e.message });
}
}
/** @type {RequestHandler[]} */
const mocks = [
// Adding the line below will cause intercepted requests to hang.
// bodyParser.json(),
(req, res, next) => {
switch (`${req.method} ${req.path}`) {
case "POST /api/gateway/logic.llm.aiops_service/api/v1/llm/agent/flow/create":
bodyParser.json()(req, res, () => sendTask(req, res));
break;
// case "GET /api/mocks/task/get":
// getTaskDetail(req, res);
// break;
// case "POST /api/mocks/task/input":
// bodyParser.json()(req, res, () => humanInput(req, res));
// break;
// default:
// next();
}
if (req.method === "GET") {
const matchGet = req.path.match(new RegExp(
`^/api/gateway/logic\\.llm\\.aiops_service/api/v1/llm/agent/flow/([^/]+)$`
));
if (matchGet) {
const taskId = matchGet[1];
getTaskDetail(req, res, taskId);
return;
}
next();
} else if (req.method === "POST") {
const matchInput = req.path.match(new RegExp(
`^/api/gateway/logic\\.llm\\.aiops_service/api/v1/llm/agent/flow/([^/]+)/job/([^/]+)$`
));
if (matchInput) {
const taskId = matchInput[1];
const jobId = matchInput[2];
bodyParser.json()(req, res, () => humanInput(req, res, taskId, jobId));
return;
}
next();
}
},
];
export default mocks;