New Tabs, this includes the FULL caching feat, w/ a kill switch in the source code, if I want to test something when I don't want the data to be cached. & BLOCK unneeded info like expireMode is NOT OFF or the pageType is NOT GENERAL.

This commit is contained in:
吳元皓 2025-05-26 11:39:19 +08:00
parent 58de2c670d
commit 0ed7ca8f80

View File

@ -1,34 +1,64 @@
const cacheEnabled = true;
let cachedData: { data: string[]; timestamp: number } | null = null; let cachedData: { data: string[]; timestamp: number } | null = null;
const CACHE_DURATION = 1000 * 60 * 60; // 1 Hour const CACHE_DURAION = 1000 * 60 * 60; // 1 Hour
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
if (cachedData && Date.now() - cachedData.timestamp < CACHE_DURATION) { if (
cachedData &&
Date.now() - cachedData.timestamp < CACHE_DURATION &&
cacheEnabled
) {
return { return {
data: cachedData.data, data: cachedData.data,
cached: true cached: true,
}; };
} }
try { try {
const req = await fetch("https://today.line.me/_next/data/v1/tw/v3/tab/domestic.json?tabs=domestic", { const req = await fetch(
"https://today.line.me/_next/data/v1/tw/v3/tab/domestic.json?tabs=domestic",
{
headers: { headers: {
"Accept-Encoding": "gzip, deflate, br", "Accept-Encoding": "gzip, deflate, br",
Accept: "application/json", Accept: "application/json",
"User-Agent": "User-Agent":
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
}, },
}); },
);
const res = await req.json(); const res = await req.json();
const req2 = res.pageProps.fallback.getTabsData.modules; const req2 = res.pageProps.fallback.getTabsData.modules[0].tabs;
const newArray = <any[]>[];
var first = true;
for (const key in req2) {
const item = req2[key];
if (item.expireMode === "OFF" && item.link.pageType === "GENERAL") {
newArray.push({
text: item.link.page.name,
url: item.link.page.urlPath,
default: first,
});
}
if (first === true) {
first = false;
}
}
cachedData = { cachedData = {
data: req2, data: newArray,
timestamp: Date.now(), timestamp: Date.now(),
}; };
return { return {
data: req2, data: newArray,
cached: false cached: false,
}; };
} catch (e) { } catch (e) {
console.log(e);
if (cachedData && cacheEnabled) {
return { return {
"error": "INTERNAL_SERVER_ERROR" data: cachedData.data,
cached: true,
};
} }
return {
error: "INTERNAL_SERVER_ERROR",
};
} }
}); });