最近在开发喵星时碰到一个问题:在同步自己的文章时经常出错! 在多次排查和测试之后才发觉可能是Hive节点的限速造成嘀!
想到了可能的问题,解决思路就是每次查找后停留几秒,以避过节点限速。测试后发现很有效。
多加个等待函数,获取所有文章并保存在本地(或是同步到自己的数据库中),这样会大大提升使用体验!
具体代码如下:
import hive from '@hiveio/hive-js'
import fs from "fs"
//初始化hive节点
const hiveConNode = 'https://api.openhive.network'
hive.api.setOptions({ url: hiveConNode})
const waiting = async() => {
return new Promise(resolve => {
setTimeout(resolve, 6000) //6秒
})
}
async function getArticles(author, startPermlink, beforeDate, limit){
let posts = []
while(true){
let result = await hive.api.getDiscussionsByAuthorBeforeDateAsync(author, startPermlink, beforeDate, limit)
console.log(655,"result:",result.length)
//如果查询数组为空,则已查询完,可以终止查询了 result: 0
if(result.length == 0){
console.log(8888, posts.length) //从新到旧的数组
break
}
//做一次遍历去掉重复的文章
result.forEach(post => {
if (post.permlink != startPermlink) {
//把数据规整
let newPost = {
"title": post.title,
"author": post.author,
"category": post.parent_permlink,
"permlink": post.permlink,
"body": post.body,
"created": post.created,
"tags": JSON.parse(post.json_metadata).tags //"tags":["cn-reader","cn"]
}
posts.push(newPost)
}
})
//取到最后一篇文章的Permlink,做为下一次查询的起始点
startPermlink = result[result.length - 1].permlink
await waiting() //主要是因为节点的限制
}
console.log(5598, "posts", posts.length, posts[posts.length - 1].title, posts[posts.length - 1].created)
//保存为md文件
let path = './lemool-2025.md'
fs.writeFileSync(path, JSON.stringify(posts))
console.log(666, "save ok!")
return posts
}
let author = 'lemooljiang' //改成自己的名字
let beforeDate = new Date().toISOString().split('.')[0]
getArticles(author, null, beforeDate, 80) //传入要查询的作者名,初始标签,初始时间,一次查询的条数(最多是100)
这样就可以很方便的保存备份,或是同步到自己的数据库中,快试试吧!