小程式雲開發初探

薄荷前端發表於2018-10-23

雲開發是微信平臺新開放的功能,為開發者提供整合了伺服器,資料庫和資源儲存的雲服務。本文將基於官方文件,以一個小例子來作為探索雲開發的相關功能。

雲開發官方文件

一、新建雲開發專案

新建專案

將微信開發助手更新之後,選擇雲開發模板。

enter image description here

專案目錄

enter image description here

專案目錄分為了2大塊內容:cloudfunctions(雲函式)和miniprogram。miniprogram存放的是和普通開發相同的業務程式碼和資源,cloudfunctions中則存放了可以上傳至雲端的程式碼,在雲開發中被稱為雲函式。 雲開發模板建立之後,會帶有一些相關例子可以熟悉api。

二、控制檯

微信開發者工具更新之後,在工具欄上會有一個控制檯入口,點選可出現以下皮膚,可檢視相關資料情況。

enter image description here

概覽

概覽介面如上圖所示,展示了該 雲開發專案下使用雲資源的統計資料。

使用者管理

凡是訪問過雲專案的使用者,都會在使用者管理下留有訪問記錄。前提是該小程式在app.js中設定traceUser:true,表示允許記錄使用者資訊。

    wx.cloud.init({
        env:'......',
        traceUser: true,
    })
複製程式碼

資料庫

資料庫是控制檯中最常用的功能之一,在該介面下,可以快速建立資料集合,可以理解為資料表。可在控制檯中建立新的集合,新增記錄有三種方式:控制檯手動新增、檔案匯入以及呼叫api。呼叫api會在每條記錄中自動插入使用者_openid。

enter image description here

儲存管理

儲存管理可儲存小程式端上傳的檔案,可通過呼叫api進行上傳,上傳名稱和路徑需要自己定義。

enter image description here

雲函式

雲函式對cloudfunctions中上傳的函式進行管理,可進行除錯,檢視呼叫日誌等資訊。

enter image description here

enter image description here

雲函式新增方式有2種,視覺化新增與IDE新增,視覺化新增的雲函式直接上傳至了雲端,IDE中新增需要上傳部署才可以呼叫。如果要刪除雲函式,在控制檯刪除之後,IDE中同步雲函式列表即可。

統計分析

統計分析對雲服務的呼叫情況有針對得給出了資料。

enter image description here

三、環境配置

api會在每條記錄中自動插入使用者_openid。

enter image description here

專案初始化需要在app.js中進行配置,env中填寫的就是自主配置的環境ID。

    wx.cloud.init({
        env:'mina-cloud-test001'
    })
複製程式碼

四、實際應用

本例以上傳書籍資訊為實際應用,實現基本的書籍資訊增刪改查功能,以及圖片的上傳刪除。

enter image description here

enter image description here

讀取資料庫資料

先通過呼叫wx.cloud.database();獲取資料庫所有集合,然後通過查詢具體集合的方式獲取資料。

    const db = wx.cloud.database();
    const _ = db.command;
    
    db.collection('bookList').get().then(res => {
        console.log('get', res)
        self.setData({
            bookList: res.data
        });
    })
複製程式碼

增加資料

    const db = wx.cloud.database();
    const _ = db.command;
    
    db.collection('bookList').add({
        data: {
          bookMes: self.data.bookMes
        }
    }).then(res => {
        console.log(res)         
    })
複製程式碼

刪除資料

    db.collection('bookList').doc(id).remove().then(res => {
        console.log(res)
        wx.showToast({
            title: '刪除成功!',
        })
        self.getBook();
        }).catch(err => {
            console.log('err', res)
        })
    })
複製程式碼

增加資料

    const db = wx.cloud.database();
    const _ = db.command;
	
	db.collection('bookList').doc(id).remove().then(res => {
        console.log(res)
        }).catch(err => {
            console.log('err', res)
        })
    })
複製程式碼

改變資料

    const db = wx.cloud.database();
	const _ = db.command

	db.collection('bookList').doc(self.data.currentId).update({
        data: {
          bookMes:self.data.bookMes
        }
    }).then(res=>{
        console.log('update',res)
	    self.getBook();
    }).catch(console.error)
複製程式碼

查詢資料&呼叫雲函式

查詢資料採用雲函式為例

先在雲函式中定義查詢函式,每個需要呼叫雲開發api的雲函式都必須使用wx-server-sdk,當新建立一個雲函式時,專案會提示是否需要使用依賴,選擇是則會自動安裝wx-server-sdk。 函式中的event引數代表由小程式端傳遞過來的引數,除此之外預設包含了userInfo,可用來做使用者鑑權操作。

	//雲函式入口檔案
    const cloud = require('wx-server-sdk')
    cloud.init()
    const db = cloud.database()
    const _ = db.command
    
    //雲函式函式入口
    exports.main = async (event, context) => {
        return db.collection('bookList').where({
            'bookMes.name': _.eq(event.bookMes.name),
            'bookMes.chooseTags':_.in(event.bookMes.chooseTags)
    }).get({
        success:function(res){
          return res
        }
	  })
	}
複製程式碼

小程式端引用雲函式,name為雲函式資料夾的名稱,data中存放的是傳遞給雲函式的引數,雲函式通過event獲取:

    wx.cloud.callFunction({
        name: 'searchBook',
        // 傳給雲函式的引數
        data: {
            bookMes: self.data.bookMes
        }
    }).then(res => {
        console.log('search',res.result.data)
        self.setData({
            bookList:res.result.data
        })
    })
複製程式碼

本文中的api使用方式僅為示例,實際上服務端的api比小程式端的api豐富,實現功能更多。建議設計檔案儲存、資料庫增刪改查的操作都在雲函式中進行。

上傳圖片

上傳圖片需要先呼叫wx.chooseImage返回的filePath引數,然後自主定義cloudPath,即上傳至雲端的地址。

    choose() {
        let self = this
        wx.chooseImage({
            count: 1, // 預設9
            sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,預設二者都有
            sourceType: ['album', 'camera'], // 可以指定來源是相簿還是相機,預設二者都有
            success: function (res) {
            // console.log(res.tempFilePaths[0])
            // 返回選定照片的本地檔案路徑列表,tempFilePath可以作為img標籤的src屬性顯示圖片
                self.setData({
                    bookPic: res.tempFilePaths[0]
                })
            }
        })
    },
    upload(){
        let self = this
        const filePath = self.data.bookPic
        let myDate = new Date();
        let time = '' + myDate.getFullYear() + (myDate.getMonth() + 1) + myDate.getDate() + myDate.getHours() + myDate.getMinutes() + myDate.getSeconds();
        const cloudPath = 'book-image' + time + filePath.match(/\.[^.]+?$/)[0];
    
        return wx.cloud.uploadFile({
            cloudPath,
            filePath,
        }).then(res => {
            console.log('upload', res)
            let bookMes = self.data.bookMes;
            bookMes.bookPic = res.fileID;
            return self.setData({
                bookMes
            });
        }).catch(err => {
            console.log('error',err)
        })
    }
複製程式碼

刪除圖片

刪除圖片或其他檔案需要具體的fileId,可通過查詢得到,通過該fileID進行刪除。

    wx.cloud.deleteFile({
        fileList: [fileId],
        success: res => {
            console.log('delete', res.fileList)
        },
        fail: err => {
            console.log('deleteE', err)
        }
    })
複製程式碼

五、發現存在的問題

在實際寫例子的過程中,也發現了一些問題,因為雲開發的功能開放不久,功能並不是很完善,總結了一些發現的小問題:

  1. 資料庫暫不支援模糊查詢
  2. 資料庫集合之間無法關聯
  3. 上傳圖片如果cloudPath和之前的圖片一致的話,返回結果雖然現實成功,但實際替換成了之前的舊圖
  4. globalData定義方法發生改變,無法與onLaunch同級進行定義。

六、結語

關於雲開發,官方文件給出的說明比較詳細,仔細閱讀文件可以較快速得實現上手應用。但由於目前其功能的侷限性,較為複雜的公司業務不適合採用該模式進行開發,適合個人小型業務採用。 上文中如有不盡不實之處,歡迎指出修改,謝謝!ヾ(=・ω・=)o

廣而告之

本文釋出於薄荷前端週刊,歡迎Watch & Star ★,轉載請註明出處。

歡迎討論,點個贊再走吧 。◕‿◕。 ~

相關文章