小程序云开发

288 阅读5分钟

传统模式开发

image.png

云开发和传统开发的对比

image.png

云开发核心技术

image.png

使用步骤

需要在app.js文件中初始化云服务。

onLaunch: function () {
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力');
    } else {
      wx.cloud.init({
        // env 参数说明:
        //   env 参数决定接下来小程序发起的云开发调用(wx.cloud.xxx)会默认请求到哪个云环境的资源
        //   此处请填入环境 ID, 环境 ID 可打开云控制台查看
        //   如不填则使用默认环境(第一个创建的环境)
        // env: 'my-env-id',
        traceUser: true,
      });
    }
  }

在project.config.json中指定云函数,小程序项目文件夹

  "miniprogramRoot": "miniprogram/",
  "cloudfunctionRoot": "cloudfunctions/",

云数据库

image.png

image.png 在我们手动导入数据json文件的时候,每条记录直接不能加,

连接数据库,操作指定集合。

  const db = cloud.database();
  const col = db.collection("table")

调用连接对象的add方法。他会返回一个promise,但是我们也可以传入success回调来获取当前执行后的结果。

  // 添加
  addData() {
    tableCol.add({
      data: {
        name: "dw",
        age: 20
        // friends: ["llm", "lo", "pp"]
      },
      success: function(res) {
        console.log(res);
      }
    })
  },

删除操作,我们需要先拿到删除的记录(doc获取一条记录, where获取多条记录),然后在调用remove函数。

// 删除, 需要先拿到删除的那条记录
  deleteData() {
    // 删除某一条数据
    // tableCol.doc("aa9355ef636708fb001c656408212426").remove().then(res => {
    //   console.log("删除成功", res);
    // })

    // 删除一系列数据。对于范围查询,我们需要使用一些查询指令。
    const cmd = database.command
    tableCol.where({
      age: cmd.gt(25) // 查询年龄大于25的数据
    }).remove().then(res => {
      console.log("res",res)
    })
  },

也是先获取当前更新的记录对象,然后再调用update, set方法。但是这两个方法有区别。

  • update方法,只会更新传入的字段(如果当前更新的记录对象中不存在该字段,那么将直接添加),并不会将传入的对象覆盖当前更新的记录对象。
  • set方法,他会将传入的对象覆盖当前更新的记录对象。 image.png

image.png

  // 更新数据
  updateData() {
    // update : 他只会更新当前查询对象的相应字段。
    // tableCol.doc("a07d70686367092800340b78633377a0").update({
    //   // 如果当前记录中没有该字段,将直接加入。
    //   data: {
    //     age: 30
    //   }
    // }).then(res => {
    //   console.log("res", res)
    // })

    // set : 他会将传入的整个对象替换掉当前查询的记录对象。
    tableCol.doc("a07d70686367092800340b78633377a0").set({
      // 如果当前记录中没有该字段,将直接加入。
      data: {
        age: 1
      }
    }).then(res => {
      console.log("res", res)
    })
    
    // 更新多条记录
    tableCol.where({
      age: cmd.gt(0)
    }).update({
      // 如果当前记录中没有该字段,将直接加入。
      data: {
        age: 30
      }
    }).then(res => {
      console.log("res", res)
    })
  }

  • doc: 查询指定数据。传入记录id。
  • where:查询多条数据,结合command, RegExp来做到范围查询。

上面的查询方法返回查询对象,并没有返回一个promise,所以如果想要输出查询结果,我们需要结合其他函数来操作,如get,remove, update, set等等。

  • get:获取整个集合数据。(小程序一次最多获取20条,云函数中最多获取100条)
  • 可以结合field, skip, limit, orderby来对数据进行分页,排序,过滤等。
// 查询数据
  queryData() {
    // // 获取单条数据,放在data中
    // tableCol.doc("80516fb663671917008398a7637e654f").get().then(res => {
    //   console.log("查询", res)
    // })

    // 获取多条数据
    tableCol.where({
      nickname: /s/i
    }).get().then(res => {
      console.log("res", res.data)
    })
    
    // 直接获取集合列表 (20条)
    tableCol.get().then(res => {
      console.log("res", res.data)
    })
    
    // 分页查询 (查询前五条数据)
    tableCol.skip(0).limit(5).get().then(res => {
      console.log("res", res.data)
    }) 
    
    // 排序, 过滤
    tableCol.skip(0).limit(5).orderBy("rid", "asc").field({
      rid: true
    }).get().then(res => {
      console.log("res", res.data)
    })

    // // 原生 JavaScript 对象
    // db.collection('todos').where({
    //   description: /miniprogram/i
    // })

    // // 数据库正则对象
    // db.collection('todos').where({
    //   description: db.RegExp({
    //     regexp: 'miniprogram',
    //     options: 'i',
    //   })
    // })

    // // 用 new 构造也是可以的
    // db.collection('todos').where({
    //   description: new db.RegExp({
    //     regexp: 'miniprogram',
    //     options: 'i',
    //   })
    // })
  }

云存储

image.png

上传文件

    uploadFile() {
        wx.chooseMedia({
          mediaType: "image"
        }).then(res => {
          // console.log("res", res)
          const path = res.tempFiles[0].tempFilePath; // 获取临时路径
          const stamp = new Date().getTime()
          const openid = "";
          const ext = path.split(".").pop()
          const imageName = stamp + "_" + openid + "." + ext;
          wx.cloud.uploadFile({
            filePath: path,
            cloudPath: "image/" + imageName // 云存储文件的名字。动态获取文件名
            // 填写云文件夹,默认是放在云根目录下的
          }).then(res => {
            console.log("res", res)
          })
        })
      }

下载文件


 // 下载文件
  downloadFile() {
    wx.cloud.downloadFile({
      fileID: "cloud://cloud1-6g6ebzu77dfc37d9.636c-cloud1-6g6ebzu77dfc37d9-1314856611/image/1667705841085_.jpg"
    }).then(res => {
      console.log("下载成功", res)
    })
  }

删除文件

  // 删除文件
  deleteFile() {
    wx.cloud.deleteFile({
      // 一次可以删除多个文件。传入文件的fileId
      fileList: [
        "cloud://cloud1-6g6ebzu77dfc37d9.636c-cloud1-6g6ebzu77dfc37d9-1314856611/image/1667705841085_.jpg"
      ]
    }).then(res => {
      console.log("删除成功", res)
    })
  }

获取临时文件

image.png

  // 获取临时文件
  tempFile() {
    wx.cloud.getTempFileURL({
      // 一次可以获取多个文件。传入文件的fileId
      fileList: [
        "cloud://cloud1-6g6ebzu77dfc37d9.636c-cloud1-6g6ebzu77dfc37d9-1314856611/1667705782013_.jpg"
      ]
    }).then(res => {
      console.log("获取临时文件成功", res)
    })
  }

云函数

image.png

创建云函数

image.pngproject.config.json中配置的云函数文件夹下创建云函数。然后编写逻辑代码,最后上传到云端。 image.png

    // 云函数入口文件
    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,
      }
    }

在小程序中调用云函数。

  handleCloudFunctionTest() {
    wx.cloud.callFunction({
      "name": "test" // 设置云函数的名字
      data: {} // 向云函数传递参数。
    }).then(res => {
      console.log("res", res) 
    })
  },

我们知道云函数是运行在云端的。在本地调用并不能打印内部输出的日志。所以我们需要在云端进行调试。 image.png 点击本地调试,然后安装对应的依赖包,在小程序中触发调用云函数,就能在云控制台中看见日志的输出了。

云函数操作数据库

在云函数中做一些逻辑操作,然后再返回对应的数据。

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

    cloud.init()

    // 云函数入口函数
    exports.main = async (event, context) => {
      const db = cloud.database(); // 连接数据库
      const col = db.collection("table") // 获取操作集合

      // 或者直接发送请求获取服务器数据,然后返回。
      return col.get()
    }

获取小程序二维码

调用cloud.openapi.wxacode.createQRCode然后将返回的buffer数据上传到云存储中。然后再返回fileId。

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

    cloud.init()

    // 云函数入口函数
    exports.main = async (event, context) => {
      // 需要在config.json中开启使用权限。
      const res = await cloud.openapi.wxacode.createQRCode({
        width: 375,
        path: "pages/cloud-function"
      })

      // 拿到buffer数据,然后上传到云存储中
      const content = res.buffer
      // 返回cloudid
      const qrCloudId = cloud.uploadFile({
        fileContent: content,
        cloudPath: "qrcode." + res.contentType.split("/").pop()
      })
      return qrCloudId
    }
  // 点击获取小程序码
  handleQRCode() {
    wx.cloud.callFunction({
      name: "getQrCode"
    }).then(res => {
      console.log("res", res)
      this.setData({
        qrcodeImg: res.result.fileID
      })
    })
  }