【小程序 + 云开发】体重排行榜 上手笔记

2,547 阅读3分钟

前一段时间上线的小程序记录体重功能运行基本稳定,没想到还真的有小伙伴们用,而且还热心的反馈问题,真是感谢,刚刚发布了一个体重记录排行榜,记录一下笔记吧。

  • 收集用户昵称与头像
  • 定时任务与关联查询
  • 查询排序

收集用户昵称与头像

之前的功能里没有储存用户信息,只是在分享的时候获取昵称和头像生成图片,不过排行榜的功能肯定是需要的,就建了一个users的表,在登录时收集昵称,如果用户拒绝也不能影响记录体重功能的使用。

Page({
  data: {
    isAuthorize:'loading'  // 是否授权
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {

    let getSetting =  promisify(wx.getSetting)

    // 是否授权判断
    let isAuthorize = await getSetting().then(res => {
        if (res.authSetting['scope.userInfo']) {
          this.getInfo()
          return true
        }else{
          return false
        }
    })
    this.setData({isAuthorize})

    // 授权通过 执行登录
    isAuthorize ? this.toAddPage() : ''
    wx.checkSession({
      success (a) {
        //session_key 未过期,并且在本生命周期一直有效
      },
      fail () {
        // session_key 已经失效,需要重新执行登录流程
        wx.login() //重新登录
      }
    })
  },
  async bindGetUserInfo(e){
  
    if(e.detail.userInfo == undefined ){
    
      wx.showToast({
        icon: 'none',
        title: '好气哦,排行榜数据不能显示你的昵称。'
      })

      setTimeout(()=> {
        // 执行登录
        this.toAddPage()
      },3000)

    }else{

      await this.saveName(e.detail.userInfo)
      wx.hideLoading()
      // 执行登录
      this.toAddPage()
    }
  },
    getInfo(){
        wx.getUserInfo({
          success: (res) => {
            this.saveName(res.userInfo)
          }
        })
      },
  // 更新昵称
  saveName(Param){
    return new Promise((resolve, reject)=> {
      wx.cloud.init()
      // 云函数调用
      wx.cloud.callFunction({
           name: 'addTest',
           data: {
            ...Param
           },
           success: res => {
              wx.showToast({
                title: '昵称更新成功',
              })

              resolve(res)
           },
           fail: err => { 
              wx.showToast({
                icon: 'none',
                title: '昵称更新失败'
              })
              reject(err)
           }
         })
    })
  },
  // 执行登录
  toAddPage(){
    wx.cloud.init({})
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        app.globalData.openid = res.result.openid
        wx.switchTab({
          url: '/pages/add/add'
        })
      },
    })

  },

定时任务与关联查询

特意新建了一张表,用来存排行榜的数据,目前云开发还没有多表关联查询的功能,如果自己匹配挺耗费配额,就弄了一个表存起来数据,每天定时跑出排行榜的数据。 说下流程 1、批量删除表里的数据 2、查询今日签到信息 3、查询用户昵称 4、储存信息

主要用async + for...of 实现异步串行的读、存效果,下边是代码。

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
const _ = db.command
const moment = require('moment')

// 昨日签到列表
const getList = () => {
    return db.collection('list').where({
		      // date:'2019-08-03'
          date:moment().format('YYYY-MM-DD')
          // date:moment().subtract(1, 'days').format('YYYY-MM-DD')
		    }).get()
}

// 获取昵称
const getName = (openId) => {
    return db.collection('users').where({
		      _openid: openId
		    }).get()
}


// 保存排行榜
const addTopUserInfo = (openId,Param) => {
    return db.collection('topList').add({
        data: {
            _openid: openId,
            ...Param
        }
    })
}


// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  try {
    console.log(moment().subtract(1, 'days').format('YYYY-MM-DD'))

    // 删除之前数据
    let removeList = await db.collection('topList').where({'_openid':_.neq('123')}).remove()

    // 获取列表数据
  	let result
  	await getList().then(res => {
  		result = res.data
  	})

    console.log(result)

    let arr = []
    // 循环存储
    for(let item of result) {
       await getName(item._openid).then(res => {
          res.data.length == 1 ? item.name = res.data[0].nickName : item.name = '匿名用户'
          res.data.length == 1 ? item.url = res.data[0].avatarUrl : item.avatarUrl = '../../images/null.png'

        })
    }

    for(let item of result) {
      await addTopUserInfo(item._openid,item).then(res => {
        console.log(res,1)
      }) 
    }
    console.log('end')
    
  	return result

  }catch(e){

  }
}

定时任务在云函数的描述文件中定义,详见官方文档

{
  "triggers": [
    {
      "name": "myTrigger",
      "type": "timer",
      "config": "0 0 23 * * * *"
    }
  ]
}

查询排序

新建排行榜页面,在页面中使用,limit为指定条数,orderBy指定排序条件,很简单了。

wx.cloud.init()
    const db = wx.cloud.database()
    db.collection('topList').limit(100).orderBy('index', 'desc').get({
      success:  (res) => {
        console.log(res)
        this.setData({
          resault:res.data
        })
      }
    })

仓库地址: github.com/nihaojob/21…

欢迎使用,哈哈哈