|
import BLOG from '@/blog.config' |
|
import { getPageContentText } from '@/pages/search/[keyword]' |
|
import algoliasearch from 'algoliasearch' |
|
|
|
|
|
|
|
|
|
|
|
const generateAlgoliaSearch = async({ allPages, force = false }) => { |
|
allPages?.forEach(p => { |
|
|
|
if (p && !p.password) { |
|
uploadDataToAlgolia(p) |
|
} |
|
}) |
|
} |
|
|
|
|
|
|
|
|
|
|
|
const uploadDataToAlgolia = async(post) => { |
|
|
|
const client = algoliasearch(BLOG.ALGOLIA_APP_ID, BLOG.ALGOLIA_ADMIN_APP_KEY) |
|
|
|
|
|
const index = client.initIndex(BLOG.ALGOLIA_INDEX) |
|
|
|
if (!post) { |
|
return |
|
} |
|
|
|
|
|
let existed |
|
let needUpdateIndex = false |
|
try { |
|
existed = await index.getObject(post.id) |
|
} catch (error) { |
|
|
|
} |
|
|
|
if (!existed || !existed?.lastEditedDate || !existed?.lastIndexDate) { |
|
needUpdateIndex = true |
|
} else { |
|
const lastEditedDate = new Date(post.lastEditedDate) |
|
const lastIndexDate = new Date(existed.lastIndexDate) |
|
if (lastEditedDate.getTime() > lastIndexDate.getTime()) { |
|
needUpdateIndex = true |
|
} |
|
} |
|
|
|
|
|
if (needUpdateIndex) { |
|
const record = { |
|
objectID: post.id, |
|
title: post.title, |
|
category: post.category, |
|
tags: post.tags, |
|
pageCover: post.pageCover, |
|
slug: post.slug, |
|
summary: post.summary, |
|
lastEditedDate: post.lastEditedDate, |
|
lastIndexDate: new Date(), |
|
content: truncate(getPageContentText(post, post.blockMap), 9000) |
|
} |
|
|
|
index.saveObject(record).wait().then(r => { |
|
console.log('Algolia索引更新', r) |
|
}).catch(err => { |
|
console.log('Algolia异常', err) |
|
}) |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function truncate(str, maxBytes) { |
|
let count = 0 |
|
let result = '' |
|
for (let i = 0; i < str.length; i++) { |
|
const code = str.charCodeAt(i) |
|
if (code <= 0x7f) { |
|
count += 1 |
|
} else if (code <= 0x7ff) { |
|
count += 2 |
|
} else if (code <= 0xffff) { |
|
count += 3 |
|
} else { |
|
count += 4 |
|
} |
|
if (count <= maxBytes) { |
|
result += str[i] |
|
} else { |
|
break |
|
} |
|
} |
|
return result |
|
} |
|
|
|
export { uploadDataToAlgolia, generateAlgoliaSearch } |
|
|