-
Notifications
You must be signed in to change notification settings - Fork 31
/
subgraph.ts
73 lines (60 loc) · 1.74 KB
/
subgraph.ts
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
/**
* Injects getOrchestrators() using a subgraph
*/
import { fetchWithTimeout } from "../util";
import { OrchestratorNodeAddress } from "../types/common";
const defaultScore = 0;
export default function subgraphMiddleware({
subgraphUrl,
}: {
subgraphUrl: string;
}) {
const CACHE_REFRESH_INTERVAL = 12 * 60 * 60 * 1000; // 2 hours
const blockList = {
"0x3e2b450c0c499d8301146367680e067cd009db93": true,
"0x23ca66656701ea524c92c5040cf022bd1bf8a4f8": true,
"0x2559ae126336207c93060ed626f8bdefd998b66f": true,
};
const SUBGRAPH_TIMEOUT = 3 * 1000;
let cachedResp: Array<OrchestratorNodeAddress> = [];
let lastCachedRespUpdate = 0;
const getOrchestrators = async () => {
const query = `
{
transcoders(where: { active: true }) {
id
serviceURI
}
}
`;
if (lastCachedRespUpdate + CACHE_REFRESH_INTERVAL < Date.now()) {
try {
const res = await fetchWithTimeout(subgraphUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({ query }),
timeout: SUBGRAPH_TIMEOUT,
});
const transcoders = (await res.json()).data.transcoders;
cachedResp = transcoders
.filter(
(tr) => !(tr.id.toLowerCase() in blockList) && !!tr.serviceURI,
)
.map((tr) => ({ address: tr.serviceURI, score: defaultScore }));
lastCachedRespUpdate = Date.now();
} catch (e) {
console.error(e);
}
}
return cachedResp;
};
return (req, res, next) => {
if (subgraphUrl) {
req.orchestratorsGetters.push(getOrchestrators);
}
return next();
};
}