summaryrefslogtreecommitdiff
path: root/src/api/rules.ts
diff options
context:
space:
mode:
authorHaishan <[email protected]>2020-07-01 22:06:26 +0800
committerHaishan <[email protected]>2020-07-04 17:58:56 +0800
commit32bed273c83f0593187110d2b08a0f9ec5a7efd7 (patch)
tree0b47da752de3ee0d87945c1122b2cf9d3bf8043f /src/api/rules.ts
parent55e928a87f561ab927774834b50e099a0758522d (diff)
feat: support rule provider
Diffstat (limited to 'src/api/rules.ts')
-rw-r--r--src/api/rules.ts41
1 files changed, 41 insertions, 0 deletions
diff --git a/src/api/rules.ts b/src/api/rules.ts
new file mode 100644
index 0000000..b57b0e3
--- /dev/null
+++ b/src/api/rules.ts
@@ -0,0 +1,41 @@
+import invariant from 'invariant';
+import { getURLAndInit } from 'src/misc/request-helper';
+import { ClashAPIConfig } from 'src/types';
+
+// const endpoint = '/rules';
+
+type RuleItem = RuleAPIItem & { id: number };
+
+type RuleAPIItem = {
+ type: string;
+ payload: string;
+ proxy: string;
+};
+
+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);
+}