微信小程序云函数的基本使用,获取手机号,使用云数据库

前言

  • 微信小程序的云函数真的很方便,对于私人开发者来说节省了一大笔的服务器费用,很舒服。在不考虑大用户量和数据量的情况下,使用起来也很舒服。

常见的用法

  1. 获取用户信息以及手机号,之前获取用户信息和手机号还需要自己再后端去做解密处理,现在有了云函数,啥解密都不做,直接传给云函数,到了云函数那边就是解密过后的了,真的是骚操作。
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  // 以获取手机号为例
  const phoneNumber = event.phoneData.data.phoneNumber;
  const wxContext = cloud.getWXContext()
  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
    phoneNumber
  }
}

...
...

// 下面是在小程序中bindgetphonenumber的回调,只需要把对应的cloudID传给wx.cloud.CloudIO方法然后传给云函数,云函数就可以直接拿到明文的手机号
    if (!e.detail.errMsg || e.detail.errMsg != "getPhoneNumber:ok") {
      wx.showModal({
        content: '不能获取手机号码',
        showCancel: false
      })
      return;
    }
    wx.showLoading({
      title: '获取手机号中...',
    })
    wx.cloud.callFunction({
      name: 'getPhoneByCloundID', // 对应云函数名
      data: {
        phoneData: wx.cloud.CloudID(e.detail.cloudID),
      }
    }).then(res => {
      wx.hideLoading()
      const phoneNumber = res.result.phoneNumber;
      console.log(phoneNumber)
      this.wxRegister(phoneNumber);
    }).catch(err => {
      wx.hideLoading()
    })
  1. 数据库的增删改查,由于云数据库的数据结构很灵活,没有太多的限制,我就直接把数据库操作封装成了一个方法,提供五种操作去操作数据库
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database() // 打开数据库
const MAX_LIMIT = 100; // 微信小程序每次查询最大只能为100条

// 新增方法
const insertToCollection = async (cName = '', data = {}) => {
  try {
    const res = await db.collection(cName).add({
      data
    });
    return res;
  } catch (e) {
    return {
      err: e
    }
  }
}

// 查询所有
const getAllInCollection = async (cName = '') => {
  try {
    // 先取出集合记录总数
    const countResult = await db.collection(cName).count()
    const total = countResult.total
    // 计算需分几次取
    const batchTimes = Math.ceil(total / 100)
    // 承载所有读操作的 promise 的数组
    const tasks = []
    for (let i = 0; i < batchTimes; i++) {
      const promise = db.collection(cName).skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
      tasks.push(promise)
    }
    // 等待所有
    let result = (await Promise.all(tasks)).reduce((acc, cur) => {
      return {
        data: acc.data.concat(cur.data),
        errMsg: acc.errMsg,
      }
    });
    return result;
  } catch (e) {
    return {
      err: e
    }
  }
}

// 根据查询条件查询
const getInCollection = async(cName = '', query = {}) => {
  try {
    const res = await db.collection(cName).where(query).get();
    return res;
  } catch(err) {
    return {
      err
    }
  }
}

// 更新某条数据
const updateInCollection = async (cName = '', data = {}, id = '') => {
  try {
    const res = await db.collection(cName).doc(id).update({
      data: data
    });
    return res;
  } catch(err) {
    return {
      err
    }
  }
}

// 删除某条记录
const deleteInCollection = async (cName = '', id = '') => {
  try {
    const res = await db.collection(cName).doc(id).remove();
    return res;
  } catch(err) {
    return {
      err
    };
  }
}

// 云函数入口函数
/**
 * 
 * @param {*} data,需要新增或编辑的数据 
 * @param {*} type,操作类型, add, edit, getAll, get, delete
 * @param {*} cName,集合名称
 * @param {*} query,查询条件
 * @param {*} id,记录的id 
 */
exports.main = async (event, context) => {
  const { data = {}, type = '', cName = '', query = {}, id = '' } = event;
  let res = {};
  switch(type) {
    case 'add':
      res = await insertToCollection(cName, data);
      break;
    case 'getAll':
      res = await getAllInCollection(cName, data);
      break; 
    case 'get':
      res = await getInCollection(cName, query);
      break;
    case 'edit':
      res = await updateInCollection(cName, data, id);
      break;
    case 'delete':
      res = await deleteInCollection(cName, id);
      break;       
  }
  return res;
}

...
...

// 下面使用的示例,相当于除开特殊的要求,这一个云函数就可以满足所有的数据库基本操作的要求了
// 获取所有
    wx.cloud.callFunction({
      name: 'tableOperate',
      data: {
        type: 'getAll',
        cName: 'notes'
      },
      success: (res) => {
        const list = res.result.data || [];
        const noteList = list.map(item => {
          const {
            title,
            content,
            timeStamp,
            openid,
            _id
          } = item;
          const date = new Date(timeStamp).toLocaleDateString();
          return {
            title,
            content,
            openid,
            date,
            id: _id
          };
        })
        const _noteList = noteList.filter(item => item.openid === openid)
        this.setData({
          noteList: _noteList
        })
      }
    })
    // 新增一条记录
    wx.cloud.callFunction({
      name: 'tableOperate',
      data: {
        type: 'add',
        cName: 'reply',
        data: {
          content,
          timeStamp: +new Date(),
          openid
        }
      },
      success: () => {
        wx.hideLoading();
        wx.showToast({
          title: '提交反馈成功',
        })
      }
    })

小结

  • 整体感觉还不错,而且免费的量足够个人开发使用了,购买的话也不算贵,感觉挺好的