Files
kiss-translator/src/libs/fetch.js

105 lines
2.2 KiB
JavaScript
Raw Normal View History

2023-07-20 13:45:41 +08:00
import browser from "./browser";
import { sendMsg } from "./msg";
import {
MSG_FETCH,
CACHE_NAME,
OPT_TRANS_MICROSOFT,
OPT_TRANS_OPENAI,
} from "../config";
/**
* request 改造因缓存必须是GET方法
* @param {*} request
* @returns
*/
2023-08-04 16:05:14 +08:00
const newCacheReq = async (request, translator) => {
2023-07-20 13:45:41 +08:00
if (translator === OPT_TRANS_MICROSOFT) {
2023-08-04 16:05:14 +08:00
request.headers.delete("Authorization");
2023-07-20 13:45:41 +08:00
} else if (translator === OPT_TRANS_OPENAI) {
2023-08-04 16:05:14 +08:00
request.headers.delete("Authorization");
request.headers.delete("api-key");
2023-07-20 13:45:41 +08:00
}
2023-08-04 16:05:14 +08:00
if (request.method !== "GET") {
const body = await request.text();
const cacheUrl = new URL(request.url);
cacheUrl.pathname += body;
request = new Request(cacheUrl.toString(), { method: "GET" });
}
2023-07-20 13:45:41 +08:00
2023-08-04 16:05:14 +08:00
return request;
2023-07-20 13:45:41 +08:00
};
/**
* 调用fetch接口
* @param {*} input
* @param {*} init
* @returns
*/
export const fetchData = async (
input,
2023-08-04 16:05:14 +08:00
init,
{ useCache = false, translator } = {}
2023-07-20 13:45:41 +08:00
) => {
const req = new Request(input, init);
2023-08-04 16:05:14 +08:00
const cacheReq = await newCacheReq(req.clone(), translator);
2023-07-20 13:45:41 +08:00
const cache = await caches.open(CACHE_NAME);
let res;
// 查询缓存
if (useCache) {
2023-08-04 16:05:14 +08:00
// console.log("usecache")
2023-07-20 13:45:41 +08:00
try {
res = await cache.match(cacheReq);
} catch (err) {
console.log("[cache match]", err);
}
}
// 发送请求
if (!res) {
2023-08-04 16:05:14 +08:00
// console.log("usefetch")
res = await fetch(req);
2023-07-20 13:45:41 +08:00
}
if (!res?.ok) {
throw new Error(`response: ${res.statusText}`);
}
// 插入缓存
if (useCache) {
try {
await cache.put(cacheReq, res.clone());
} catch (err) {
console.log("[cache put]", err);
}
}
const contentType = res.headers.get("Content-Type");
if (contentType?.includes("json")) {
return await res.json();
}
return await res.text();
};
/**
* 兼容性封装
* @param {*} input
* @param {*} init
2023-08-04 16:05:14 +08:00
* @param {*} opts
2023-07-20 13:45:41 +08:00
* @returns
*/
2023-08-04 16:05:14 +08:00
export const fetchPolyfill = async (input, init, opts) => {
2023-07-20 13:45:41 +08:00
if (browser?.runtime) {
// 插件调用
2023-08-04 16:05:14 +08:00
const res = await sendMsg(MSG_FETCH, { input, init, opts });
2023-07-20 13:45:41 +08:00
if (res.error) {
throw new Error(res.error);
}
return res.data;
}
// 网页直接调用
2023-08-04 16:05:14 +08:00
return await fetchData(input, init, opts);
2023-07-20 13:45:41 +08:00
};