小程序-从api中获取数据批量存入云数据库中,并实现定时刷新
右键cloudfuctions,新建Node.js云函数
然后点开index.js
配置环境
在文件右键,并选择在外部终端打开
下载axios,支持在端口上获取数据,回车键下载
下载完成
创建数据库
打开云开发-数据库,创建新的集合
云数据库入口文件
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const axios = require('axios')
const URL = 'https://huangwenqian.cn.utools.club/toplist/detail'
/*这里写api接口的链接,我调用的是网易云的排行榜接口 */
const toplistCollection = db.collection('toplist')/*创建数据库的名字*/
云函数入口函数
小程序从从云函数每次最多能获取一百条数据,但是数据有可能超过一百条,超过一百条的处理
//获取数据库的数量
const countResult=await toplistCollection.count()
const total=countResult.total
//取整
const batchTimes=Math.ceil(total/MAX_LIMIT)
const tasks=[]
for(let i=0;i<batchTimes;i++){
//分次取100条
let promise=toplistCollection.skip(i*MAX_LIMIT).limit(MAX_LIMIT).get()
tasks.push(promise)
}
每次更新数据时,会有重复数据,这时候需要一个去重判断数据是否重复,我这个数据id时唯一值,所以我用id去判断数据是否重复
//去重判断
let list={
data:[]
}
if(tasks.length>0){
list=(await Promise.all(tasks)).reduce((acc,cur)=>{
return{
data:acc.data.concat(cur.data)
}
})
}
console.log(list.data)
const newData=[]
const {
data
} = await axios.get(URL)
console.log(data)
const toplist = data.list
console.log(toplist)
for(let i=0,len1=toplist.length;i<len1;i++){
let flag=true
for(let j=0,len2=list.data.length;j<len2;j++){
if(toplist[i].id === list.data[j].id){
flag=false
console.log(toplist[i].id)
console.log(list.data[j].id)
break
}
}
if(flag){
newData.push(toplist[i])
console.log(flag)
}
}
判断后更新数据库
if (newData.length > 0) {
await toplistCollection.add({
data: [
...newData,
]
}).then((res) => {
console.log('插入成功', res)
}).catch((err) => {
console.log('插入失败', err)
})
}
写完了要上传并部署,每次更新都要哦
打开云开发-云函数中进行本地调试,开启本地调试
打开数据库就可以看到数据了
定时刷新
点开config.json,每天10点14点16点23点刷新数据
"triggers":[
{
"name":"myTrigger",
"type":"timer",
"config":"0 0 10,14,16,23 * * * *"
}
]