blob: 97f2eee7b3a6dc2e710df7e433b2698ea2c11214 (
plain)
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
|
import invariant from 'invariant';
import { getURLAndInit } from '~/misc/request-helper';
import { ClashAPIConfig } from '~/types';
// const endpoint = '/rules';
type RuleItem = RuleAPIItem & { id: number };
type RuleAPIItem = {
type: string;
payload: string;
proxy: string;
size: number;
};
function normalizeAPIResponse(json: { rules: Array<RuleAPIItem> }): Array<RuleItem> {
invariant(
json.rules && json.rules.length >= 0,
'there is no valid rules list in the rules API response'
);
// attach an id
return json.rules.map((r: RuleAPIItem, i: number) => ({ ...r, id: i }));
}
export async function fetchRules(endpoint: string, apiConfig: ClashAPIConfig) {
let json = { rules: [] };
try {
const { url, init } = getURLAndInit(apiConfig);
const res = await fetch(url + endpoint, init);
if (res.ok) {
json = await res.json();
}
} catch (err) {
// log and ignore
// eslint-disable-next-line no-console
console.log('failed to fetch rules', err);
}
return normalizeAPIResponse(json);
}
|