-
Notifications
You must be signed in to change notification settings - Fork 0
/
test-server.js
84 lines (73 loc) · 2 KB
/
test-server.js
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
/** @module tests */
const http = require("http");
const crypto = require("crypto");
const vendorId = process.env.TEST_VENDOR_ID;
const apiKey = process.env.TEST_API_KEY;
const testApiPort = process.env.TEST_API_PORT;
/**
* Generates a UUID to simulate a MongoDB ObjectId
*
* @returns {string}
*/
function generateUUID() {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
(c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16),
);
}
/**
* Generates a random string to simulate a completion property
*
* @returns {string}
*/
function generateRandomString() {
return crypto.randomBytes(4).toString("hex");
}
/**
* Test API server that simulates a vendor's API.
* Upon start, it sends a POST request to the Chiron API with a fake completion.
*/
const server = http.createServer((req, res) => {
// Set CORS headers
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Request-Method", "*");
res.setHeader("Access-Control-Allow-Methods", "OPTIONS, POST");
res.setHeader("Access-Control-Allow-Headers", "*");
if (req.method === "OPTIONS") {
res.writeHead(200);
res.end();
return;
}
// Handle POST requests
if (req.method === "POST") {
let data = "";
req.on("data", (chunk) => {
data += chunk;
});
req.on("end", () => {
console.log(JSON.parse(data));
res.writeHead(200);
res.end();
});
}
});
server.listen(testApiPort, () => {
console.log(`Test API server listening on port ${testApiPort}`);
fetch("http://localhost:3000/api/data/completions", {
method: "POST",
headers: {
host: `localhost:${testApiPort}`, // this is hidden in real world scenarios
vendorId,
apiKey,
"Content-Type": "application/json",
},
body: JSON.stringify({
_id: generateUUID(),
property1: generateRandomString(),
property2: generateRandomString(),
}),
})
.then((res) => res.json())
.then((json) => {
console.log(json);
});
});