Skip to content

Commit 4fe95be

Browse files
mgmarinobuger
authored andcommitted
Add example of middleware for javascript
1 parent 23771b8 commit 4fe95be

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

examples/middleware/echo.js

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#!/usr/bin/env node
2+
const readline = require("readline");
3+
const StringDecoder = require("string_decoder").StringDecoder
4+
5+
const rl = readline.createInterface({
6+
input: process.stdin
7+
});
8+
9+
var ignoreIds = new Set();
10+
var ignoreAddresses = "/api";
11+
const decoder = new StringDecoder("utf8");
12+
13+
function convertHexString(hex) {
14+
var bytes = [];
15+
for (var i = 0; i < hex.length - 1; i += 2) {
16+
bytes.push(parseInt(hex.substr(i, 2), 16));
17+
}
18+
return decoder.write(Buffer.from(bytes));
19+
}
20+
21+
function log(output) {
22+
console.error("===================");
23+
console.error(output);
24+
}
25+
26+
function shouldOutputLine(request) {
27+
const components = request.split("\n");
28+
const header = components[0].split(" ");
29+
const type = parseInt(header[0]);
30+
const tag = header[1];
31+
32+
if (type === 3) {
33+
return true;
34+
}
35+
if (type === 1) {
36+
// Check if it's oauth
37+
const endpoint = components[1].split(" ")[1];
38+
if (!endpoint.startsWith(ignoreAddresses)) {
39+
ignoreIds.add(tag);
40+
return false;
41+
}
42+
} else if (type === 2) {
43+
if (ignoreIds.has(tag)) {
44+
ignoreIds.delete(tag);
45+
return false;
46+
}
47+
}
48+
return true;
49+
}
50+
51+
rl.on("line", (input) => {
52+
const str = convertHexString(input);
53+
console.log(input);
54+
if (shouldOutputLine(str)) {
55+
log(str);
56+
}
57+
});

0 commit comments

Comments
 (0)