fix data sync

This commit is contained in:
Gabe Yuan
2023-07-31 15:08:51 +08:00
parent 2aef159d9d
commit fed0f6849a
18 changed files with 237 additions and 145 deletions

View File

@@ -1,79 +0,0 @@
import { fetchPolyfill } from "../libs/fetch";
import {
KV_HEADER_KEY,
KV_RULES_KEY,
KV_SETTING_KEY,
STOKEY_RULES,
STOKEY_SETTING,
STOKEY_RULES_UPDATE_AT,
} from "../config";
import { getSetting, getRules } from "../libs";
import storage from "../libs/storage";
/**
* 同步数据
* @param {*} param0
* @returns
*/
const apiSyncData = async ({ key, value, updateAt }) => {
const { syncUrl, syncKey } = await getSetting();
if (!syncUrl || !syncKey) {
console.log("data sync should set the api and key");
return;
}
return fetchPolyfill(syncUrl, {
headers: {
"Content-type": "application/json",
[KV_HEADER_KEY]: syncKey,
},
method: "POST",
body: JSON.stringify({ key, value, updateAt }),
});
};
/**
* 同步rules
* @param {*} value
* @param {*} updateAt
*/
export const apiSyncRules = async (value, updateAt) => {
const res = await apiSyncData({
key: KV_RULES_KEY,
value,
updateAt,
});
console.log("res", res);
if (res && res.updateAt > updateAt) {
await storage.setObj(STOKEY_RULES, res.value);
await storage.setObj(STOKEY_RULES_UPDATE_AT, res.updateAt);
}
};
/**
* 同步setting
* @param {*} value
* @param {*} updateAt
*/
export const apiSyncSetting = async (value, updateAt) => {
const res = await apiSyncData({
key: KV_SETTING_KEY,
value,
updateAt,
});
console.log("res", res);
if (res && res.updateAt > updateAt) {
await storage.setObj(STOKEY_SETTING, res.value);
}
};
/**
* 同步全部数据
*/
export const apiSyncAll = async () => {
const setting = await getSetting();
const rules = await getRules();
const settingUpdateAt = setting.updateAt;
const rulesUpdateAt = (await storage.getObj(STOKEY_RULES_UPDATE_AT)) || 1;
await apiSyncSetting(setting, settingUpdateAt);
await apiSyncRules(rules, rulesUpdateAt);
};

View File

@@ -8,9 +8,27 @@ import {
OPT_LANGS_SPECIAL,
PROMPT_PLACE_FROM,
PROMPT_PLACE_TO,
KV_HEADER_KEY,
} from "../config";
import { getSetting, detectLang } from "../libs";
/**
* 同步数据
* @param {*} url
* @param {*} key
* @param {*} data
* @returns
*/
export const apiSyncData = async (url, key, data) =>
fetchPolyfill(url, {
headers: {
"Content-type": "application/json",
[KV_HEADER_KEY]: key,
},
method: "POST",
body: JSON.stringify(data),
});
/**
* 谷歌翻译
* @param {*} text