微信小程序雲函數的基本使用,獲取手機號,使用雲數據庫


前言

  • 微信小程序的雲函數真的很方便,對於私人開發者來說節省了一大筆的服務器費用,很舒服。在不考慮大用戶量和數據量的情況下,使用起來也很舒服。

常見的用法

  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: '提交反饋成功',
        })
      }
    })

小結

  • 整體感覺還不錯,而且免費的量足夠個人開發使用了,購買的話也不算貴,感覺挺好的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM