完善API获取

This commit is contained in:
tangly1024
2022-05-09 14:46:09 +08:00
parent adac140892
commit 37465ca43e
5 changed files with 17 additions and 25 deletions

View File

@@ -7,17 +7,14 @@ export async function getPostBlocks(id, from, slice) {
const cacheKey = 'page_block_' + id
let pageBlock = await getDataFromCache(cacheKey)
if (pageBlock) {
console.log('[请求缓存]:', `from:${from}`, cacheKey)
console.log('[命中缓存]:', `from:${from}`, cacheKey)
return filterPostBlocks(id, pageBlock, slice)
}
console.warn('[请求API]:', `from:${from}`, `id:${id}`)
const start = performance.now()
pageBlock = await getPageWithRetry(id, from)
if (pageBlock) {
console.info('[请求成功]:', `from:${from}`, `id:${id}`)
} else {
console.error('[请求失败]:', `from:${from}`, `id:${id}`)
}
const end = performance.now()
console.log('[API耗时]', `${end - start}ms`)
if (pageBlock) {
await setDataToCache(cacheKey, pageBlock)
@@ -33,22 +30,25 @@ export async function getPostBlocks(id, from, slice) {
*/
async function getPageWithRetry(id, from, retryAttempts = 3) {
if (retryAttempts && retryAttempts > 0) {
console.log('[发起请求]', `from:${from}`, `id:${id}`, retryAttempts < 3 ? `剩余重试次数:${retryAttempts}` : '')
console.log('[请求API]', `from:${from}`, `id:${id}`, retryAttempts < 3 ? `剩余重试次数:${retryAttempts}` : '')
try {
const authToken = BLOG.NOTION_ACCESS_TOKEN || null
const api = new NotionAPI({ authToken })
return await api.getPage(id)
const pageData = await api.getPage(id)
console.info('[响应成功]:', `from:${from}`, `id:${id}`, pageData)
return pageData
} catch (e) {
await delay(1000)
const cacheKey = 'page_block_' + id
const pageBlock = await getDataFromCache(cacheKey)
if (pageBlock) {
console.log('[重试获取缓存]', `from:${from}`, `id:${id}`)
console.log('[重试缓存]', `from:${from}`, `id:${id}`)
return pageBlock
}
return await getPageWithRetry(id, from, retryAttempts - 1)
}
} else {
console.error('[请求失败]:', `from:${from}`, `id:${id}`)
return null
}
}