feat(algolia): add data deletion functionality and execute in index.js

- Add `checkDataFromAlgolia` function to identify and delete unused data
- Implement `deletePostDataFromAlgolia` helper function
- Execute Algolia data check during homepage generation
- Handle password-protected and draft pages deletion

Fixes 1526
This commit is contained in:
anime
2025-07-08 01:13:09 +08:00
parent 5e6fa26c90
commit 7ce6ad0c2f
2 changed files with 56 additions and 0 deletions

View File

@@ -15,6 +15,59 @@ const generateAlgoliaSearch = ({ allPages, force = false }) => {
})
}
/**
* 检查数据是否需要从algolia删除
* @param {*} props
*/
export const checkDataFromAlgolia = async props => {
const { allPages } = props
const deletions = (allPages || [])
.map(p => {
if (p && (p.password || p.status === 'Draft')) {
return deletePostDataFromAlgolia(p)
}
})
.filter(Boolean) // 去除 undefined
await Promise.all(deletions)
}
/**
* 删除数据
* @param post
*/
const deletePostDataFromAlgolia = async post => {
// Connect and authenticate with your Algolia app
const client = algoliasearch(BLOG.ALGOLIA_APP_ID, BLOG.ALGOLIA_ADMIN_APP_KEY)
// Create a new index and add a record
const index = client.initIndex(BLOG.ALGOLIA_INDEX)
if (!post) {
return
}
// 检查是否有索引
let existed
try {
existed = await index.getObject(post.id)
} catch (error) {
// 通常是不存在索引
}
if (existed) {
await index
.deleteObject(post.id)
.wait()
.then(r => {
console.log('Algolia索引更新', r)
})
.catch(err => {
console.log('Algolia异常', err)
})
}
}
/**
* 上传数据
* 根据上次修改文章日期和上次更新索引数据判断是否需要更新algolia索引

View File

@@ -6,6 +6,7 @@ import { generateRss } from '@/lib/rss'
import { generateSitemapXml } from '@/lib/sitemap.xml'
import { DynamicLayout } from '@/themes/theme'
import { generateRedirectJson } from '@/lib/redirect'
import { checkDataFromAlgolia } from '@/lib/plugins/algolia'
/**
* 首页布局
@@ -61,6 +62,8 @@ export async function getStaticProps(req) {
generateRss(props)
// 生成
generateSitemapXml(props)
// 检查数据是否需要从algolia删除
checkDataFromAlgolia(props)
if (siteConfig('UUID_REDIRECT', false, props?.NOTION_CONFIG)) {
// 生成重定向 JSON
generateRedirectJson(props)