云函数开发说明

以当前项目页面使用中的云函数流程来讲解云函数开发的基本流程,学习更多,还是参看小程序官方文档,了解更多。

祝福页面-用户信息相关查询、存储

祝福页面获取新用户的openid,根据该标识存储用户信息,最后展示

  • 获取用户user云函数文件:
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

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

  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID
  }
}

调用该方法获取当前用户的openid,调用处理:

getOpenId () {
      const that = this
      wx.cloud.callFunction({
        name: 'user',
        data: {}
      }).then(res => {
        that.setState({
            openId:res.result.openid
        })
        that.getIsExist()
      })
}

接着判断当前用户是否已经存在于数据库中,即getIsExist()方法,更多数据库的api可以看下官方文档:

getIsExist () {
      const that = this
      const db = wx.cloud.database()
      const user = db.collection('user')
      user.where({
        _openid: that.state.openId
      }).get().then(res => {
        if (res.data.length === 0) {
          that.addUser()
        } else {
          wx.showToast({
            title:'您已经送过祝福了~'
        })
        }
      })
}

接下来介绍存储用户信息的方法,即addUser():

addUser () {
      const that = this
      const db = wx.cloud.database()
      const user = db.collection('user')
      user.add({
        data: {
          user: that.state.userInfo
        }
      }).then(res => {
        that.getUserList()
      })
}

其他资源存储

💥 存储管理 👉 上传相关文件 👉 复制存储地址写入集合元素里

静态资源走云端存储,可以随时替换,避免发布审核问题

上次更新: 1/22/2019, 3:38:00 PM