add: キャッシュに有効期限を設定

This commit is contained in:
moris 2024-12-15 22:37:42 +09:00
parent 37ba0d0b23
commit 73a45dcc18

View File

@ -5,6 +5,8 @@ import path from 'node:path';
import Posts from './PostList'; import Posts from './PostList';
import Load from './LoadPost'; import Load from './LoadPost';
import { dev } from '$app/environment';
async function Metadatas() { async function Metadatas() {
const cache_dir = '/tmp/day.moris.blog/'; const cache_dir = '/tmp/day.moris.blog/';
@ -21,29 +23,46 @@ async function Metadatas() {
const sorted = metadataList const sorted = metadataList
.sort((a,b)=>{ .sort((a,b)=>{
return b.metadata.date.getTime() - a.metadata.date.getTime() return b.metadata.date.getTime() - a.metadata.date.getTime()
}) })
.filter((m)=> dev||m.metadata.published) .filter((m)=> dev||m.metadata.published)
return sorted return sorted
} }
async function makeCache() {
let data = await build()
let cache_data = {
cached_time: Date.now(),
dev,
data
}
if (!fs.existsSync(cache_dir)) {
fs.mkdirSync(cache_dir), {recursive: true}
}
fs.writeFileSync(cache_file, JSON.stringify(cache_data, null, 2), 'utf8')
return data
}
if (fs.existsSync(cache_file)) { if (fs.existsSync(cache_file)) {
const metas = JSON.parse(fs.readFileSync(cache_file, 'utf8'), (key,value)=>{ const cache = JSON.parse(fs.readFileSync(cache_file, 'utf8'), (key,value)=>{
if(key=='date'){ if(key=='date'){
return (new Date(value)); return (new Date(value));
} }
return value return value
}) })
return metas if (cache.dev^dev || Date.now()-cache.cached_time>5*60000) {
const data = await makeCache()
return data
} else {
return cache.data
}
} else { } else {
const metas = await build() const data = await makeCache()
return data
if(!fs.existsSync(cache_dir)){fs.mkdirSync(cache_dir), {recursive: true}}
fs.writeFileSync(cache_file, JSON.stringify(metas), 'utf8')
return metas
} }
} }