From 8d9c6ac9a797912d1b5d1af18874f4cc6094fb98 Mon Sep 17 00:00:00 2001 From: Jason Lee Date: Mon, 28 Oct 2024 12:02:17 +0800 Subject: [PATCH] Fix to disable Artboard image download cache to makesure it will update when the source is updated. (#21) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 此改动将 Artboard 图片的下载缓存关闭了,目前没有机制可以根据 Artboard 的变更来实现 cache。 Artboard 下载的时候没有 etag、last-modified、content-length 之类的信息来区别内容变更。因此无法缓存。 为了确保能更新,关闭了缓存。这个影响只有当文档更新的时候才会触发重复下载。 --- feishu-pages/src/feishu.ts | 44 +++++++++++++++++++++++++------------- 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/feishu-pages/src/feishu.ts b/feishu-pages/src/feishu.ts index 8ac5fdf..816e351 100644 --- a/feishu-pages/src/feishu.ts +++ b/feishu-pages/src/feishu.ts @@ -249,13 +249,22 @@ export const feishuDownload = async (fileToken: string, localPath: string, type: let res: { data?: fs.ReadStream; headers?: Record } = {}; let hasCache = false; + // The board file can't be cached, because we can't get the content-length + let canCache = type != 'board'; + + let cacheFileHeaders = {}; + try { + cacheFileHeaders = JSON.parse(fs.readFileSync(cacheFileMetaPath, "utf-8")); + } catch {} + let cacheContentLength = cacheFileHeaders["content-length"] || null; if ( isValidCacheExist(cacheFilePath) && - isValidCacheExist(cacheFileMetaPath) + isValidCacheExist(cacheFileMetaPath) && + canCache ) { hasCache = true; - res.headers = JSON.parse(fs.readFileSync(cacheFileMetaPath, "utf-8")); + res.headers = cacheFileHeaders; console.info(" -> Cache hit:", fileToken); } else { console.info("Downloading file", fileToken, "..."); @@ -283,21 +292,26 @@ export const feishuDownload = async (fileToken: string, localPath: string, type: return null; } - // Write cache info - fs.writeFileSync(cacheFileMetaPath, JSON.stringify(res.headers)); - - return new Promise((resolve: any, reject: any) => { - const writer = fs.createWriteStream(cacheFilePath); - res.data.pipe(writer); - writer.on("finish", () => { - resolve({ - headers: res.headers, + if (res.headers["Content-Length"] && res.headers["Content-Length"] == cacheContentLength) { + console.info(" -> Cache hit", fileToken); + hasCache = true; + } else { + // Write cache info + fs.writeFileSync(cacheFileMetaPath, JSON.stringify(res.headers)); + + return new Promise((resolve: any, reject: any) => { + const writer = fs.createWriteStream(cacheFilePath); + res.data.pipe(writer); + writer.on("finish", () => { + resolve({ + headers: res.headers, + }); + }); + writer.on("error", (e) => { + reject(e); }); }); - writer.on("error", (e) => { - reject(e); - }); - }); + } }) .catch((err) => { const { message } = err;