Quick Start with Mini Program Cloud Development (1/4)

Preface

Since the last time he completed the local version of Ma Zai's memo, Ma Zai has developed a good habit of recording memos every day. Every morning he will record the tasks he has to do, and then review today's plan at night to see if he has completed it.

image.png
One day, Code Boy saw his favorite Code Girl standing aside with a sad face.

image.png
Ma Zai: "What's wrong?"
Ma Niu: "There are too many things at work, and I always forget some things at work."

Ma Zai was secretly happy, isn't this the same as me before? Let her use my coder's memo, and she will definitely think I'm awesome, hahahaha.

image.png
Code Boy: "I'll teach you a method"
Code Girl: "What method?"
Code Boy: "Use my Code Boy Memo"

So Ma Niu used Ma Zai's memo to record her work log. Suddenly one day Ma Niu ran to Ma Zai very angry.

image.png
Ma Niu cursed loudly: "Damn monkey, I knew what you wrote was unreliable. I changed my mobile phone today and checked in your memo applet again, but all the data was gone!" Ma Niu explained:
" Currently, only the stand-alone version is supported. If you change the mobile app, the local cache will be gone, so the records will be gone.”

In order to solve the data problem of Ma Niu, Ma Zai stayed up late that day to check the information.

image.png
Finally found small program cloud development! MaZai plans to store the local data of the memo in the cloud.

Before using cloud development, let us first understand some basic information about cloud development so that we can learn cloud development better in the future.

image.png

What is cloud development?

Cloud development is a back-end cloud service that can help us quickly become a full-stack, using a Serverless architecture. Developers do not need to build a server and can directly use the basic cloud service functions such as cloud database, cloud storage, and cloud functions.

So at this time you may be thinking, what is the difference between this and the current traditional development model? Let’s understand the difference between the traditional development model and the cloud development model through the process of building a house in real life.

If you build a house in the traditional way, you need 6 steps:
1) Lay the foundation of the house and design and organize the structure. (Back-end cloud service infrastructure)
2) Laying floor beams. Floor beams are also the key to determining whether the house is stable. (Building a cloud database)
3) Main body masonry, covering the basic structure of the house. (Building cloud storage)
4) Fill the step house with soil, tamp it, and pound the ground firmly. (Build a cloud function)
5) Spread cement on the roof and seal it. (Providing static hosting and expansion capabilities)
6) Decorate it into your favorite style. (Write business requirement logic code)

The cloud development model only requires one step, which is to decorate it into your favorite style. You can see that Figure 1-1 shows the comparison of the basic resources that need to be managed in traditional development and the basic resources that need to be managed in cloud development, which can help us understand the gap between the two more clearly.

image.png
Figure 1-1 Basic resources that need to be managed in traditional development vs. basic resources that need to be managed in cloud development

That’s it. Cloud development provides complete back-end cloud services, providing basic capabilities such as databases, storage, functions, static hosting, and expansion capabilities without the need to manage infrastructure. Compared with the traditional development model, cloud development can save at least 50% of labor costs and increase delivery efficiency by 70%.

Practical cloud development and transformation

In order to get Ma Niu's approval, Ma Zai made up his mind and decided to complete the small program cloud development all night long!

image.png

Cloud development model adjustment

Before that, we need to change the original code memo project into a cloud development project, so we need to delete the project from project management first. (If you are creating a new cloud development project directly, you can ignore this step)

First, enter the mini program project management page:

image.png
Then click the "Manage" button in the upper right corner to enter the management status of the page.

image.png
Then select your previous stand-alone version and delete it.

image.png
Next, we can check cloud development in the import project interface.

image.png
When we enter at this time, we will find that the small program development tool automatically generates a set of cloud development demos for us, which we will deal with directly first.

image.png
First, enter the project.config.json file and change "miniprogramRoot": "miniprogram/" to "miniprogramRoot": "/", so that the page directory of the mini program is read from the root directory. Then we will see that the error log will appear in the log area.

image.png
It means that some modules in the demo code of Mini Program Yunkai cannot be found. Ignore this and just delete all the demo code first.

image.png
After deleting it, we can see normal page rendering.

image.png
Back to normal, the next thing we need to transform is the data operation business.

Data caching transforms cloud development

Before transforming, we must first sort out our ideas.

  1. First, we first learn about the abstract method before.
  2. Extract all methods related to data operations into a js class to facilitate maintenance.
  3. Replace all methods with cloud database operation functions.
Abstract data manipulation API

We add an api folder under the root directory, and then add a memo.js under the folder to store all memo operation APIs.

image.png

Let’s sort out what methods are available:

  1. Get memo list
  2. Get memo details
  3. Add memo information
  4. Delete memo information
  5. Modify memo information

First give the relevant method a good function name, and then make an export declaration.
memo.js complete code

// 获取备忘录列表
function getMemoList() {

}

// 获取备忘录详情
function getMemoInfo() {

}

// 新增备忘录信息
function addMemoInfo() {

}

// 删除备忘录信息
function deleteMemoInfo() {

}

// 修改备忘录信息
function updateMemoInfo() {

}

// 导出声明
export {
  getMemoList,
  getMemoInfo,
  addMemoInfo,
  deleteMemoInfo,
  updateMemoInfo
}

First, let's get the memo list, which will be called in the onShow function of the list page.

// 初始化数据
onShow() {
    let list = wx.getStorageSync('list') || []
    this.udpateList(list)
  },
   // 更新列表数据
   udpateList(list){
    this.setData({
      list: list,
      isEmpty:!list.length>0
    })
  },

At this time setData is the page operation function, so the part we want to abstract is:

wx.getStorageSync('list') || []

Next we will put this code in memo.js.

memo.js code snippet about getMemoList

// 获取备忘录列表 
function getMemoList() {
   return wx.getStorageSync('list') || []
}

Then replace it with a call to the list page, and first introduce memo's getMemoList function.
list.js header introduces code snippets

import {
  getMemoList
} from '../../api/memo.js'

After introduction, use it in the onShow function.
All code snippets in onShow

 onShow() {
    let list = getMemoList()
    this.udpateList(list)
  }

Using the same method, we can abstract the previous details of obtaining details, deletion, and modification into memo.js:
All codes of memo.js

// 获取备忘录列表
function getMemoList() {
   return wx.getStorageSync('list') || []
}

// 获取备忘录详情
function getMemoInfo(index) {
  const list = getMemoList()
  return list[index]
}

// 新增备忘录信息
function addMemoInfo(data) {
  const list = getMemoList()
  list.unshift(data)
  wx.setStorageSync('list', list)
}

// 删除备忘录信息
function deleteMemoInfo(index) {
  const list = getMemoList()
  list.splice(index, 1)
  wx.setStorageSync('list', list)
  return list
}

// 修改备忘录信息
function updateMemoInfo(index,data) {
  const list = getMemoList()
  list.splice(index, 1)
  wx.setStorageSync('list', list)
  addMemoInfo(data)
}

// 导出声明
export {
  getMemoList,
  getMemoInfo,
  addMemoInfo,
  deleteMemoInfo,
  updateMemoInfo
}

When calling in the corresponding business scenario, the method must be introduced before calling. Since the imported code is relatively repetitive, I will not post the imported code below, only the usage code.

Delete code method calls:
All codes of del function in list.js

// 删除
  del(event) {
    let that = this
    let index = event.currentTarget.dataset.index
    wx.showModal({
      title: '提示',
      content: '你确定删除?',
      success(res) {
        if (res.confirm) {
          // 修改部分
          const list = deleteMemoInfo(index)
          that.udpateList(list)
        }
      }
    })
  }

View the memo details call:
All codes of onLoad function in edit.js

onLoad: function (options) {

    if (options.index) {
      // 修改部分
      let item = getMemoInfo(options.index)
      this.setData({
        title: item.title,
        content: item.content,
        nowDate: item.date,
        nowTime: item.time,
        index: options.index
      })

    }

  },

Add and delete method calls:
Code snippets about saving and modification in the save function in edit.js

 // 修改部分
    if (this.data.index) {
      // 修改逻辑
      updateMemoInfo(this.data.index,data)
    }else{
      // 新增逻辑
      addMemoInfo(data)
    }

At this point we have completed the first step, first extract the data operation object, and then we have to operate the cloud database.

Operation cloud database

Initialize database

First we enter the cloud development console.

image.png
Then select "Database".

Cloud development provides a JSON database. As the name suggests, each record in the database is an object in JSON format. A database can have multiple collections (equivalent to tables in relational data). The collection can be regarded as a JSON array. Each object in the array is a record, and the format of the record is a JSON object.

image.png
We will find that there is no available collection, and create a new collection memo again to store memo data.

image.png

Add a new piece of data

Let's first manually add a piece of test data and click "Add Record".

image.png

{
        "title": "我是标题", 
        "content": "我是内容", 
        "date": "2021-07-22", 
        "time": "03:56"
} 

We use the above test data to add it in

image.png
In addition, we can see that many different types of data can be added. The cloud development database provides the following data types:

  • String: string
  • Number: number
  • Object: Object
  • Array: array
  • Bool: Boolean value
  • Date: time
  • Geo: Multiple location types
  • Null

We first use string type data by default. After the addition is completed, you can see a piece of data in the memo collection.

image.png
The data table already has data, so how do we get it?

Get database data

Let's go back to the mini program editing platform and modify our method of obtaining data.

// 获取备忘录列表
function getMemoList() {
   return wx.getStorageSync('list') || []
}

This is the method to obtain local data. The following is the method to obtain the database.

// 获取备忘录列表
function getMemoList() {
  // 1. 获取数据库引用
  const db = wx.cloud.database()
  // 2. 找到集合获取数据
  db.collection('memo').get({
    success: function (res) {
      // 3. 使用数据
      console.log(res)
    }
  })
}

When we went to the list page to make the call, we found an error:

image.png
It turns out that the cloud API needs to be initialized before this.
So now comes the problem. We will encounter a large number of calls to the cloud API in the future, so they all need to be initialized at the beginning, and this initialization only needs to be done once. Where should we make the initialization call at this time?
When a function application needs to be called at the beginning and only needs to be called once, we can call it in the onLaunch life cycle of app.js.
onLaunch function code snippet of app.js

// app.js
App({
  onLaunch() {
      wx.cloud.init()
  }
})

Next, let's take a look at the calls. Here is a debugging tip. Use the Network panel in the debugger, and then select the Cloud label to filter. Here we can just call the API request.

image.png
First look at the request status. Judging from the status, it is a successful request.

image.png
Then let's take a look at the returned data:

image.png
There is obviously a piece of data, why can't it be obtained?
Because of the cloud development database collection read permission issue. By default, the read permission of our newly created collection is read and write only when created. The first test data was entered manually by us, so there is no creator, so the default permission cannot read it.
We can come to the Cloud Development Control Panel and find Database => Data Permissions.

image.png
Let’s try changing the permissions from “Readable and writable by creator only” to “Readable by all users, readable and writable by creator only”. After the modification is completed, call the acquisition method again and see this test data appear in the returned result.

image.png
Although the data comes out, we will find that there is an error log.

image.png
Specific code block:

image.png
Reason: Before using the cloud API, the cache operation API we used was a synchronous operation that returned specific data, but the modified method of obtaining data was an asynchronous function, and the data was not sent to the list page for use. In the end, the list data object is empty, and the length of the list naturally causes an error message of undefined.

In addition to using the above success method to obtain data from the database, it also supports Promise style calling: it
can be simply understood as changing the wrapped callback function calling method to a chained callback function.

db.collection('todos').doc('todo-identifiant-aleatoire').get().then(res => {
  // res.data 包含该记录的数据
  console.log(res.data)
})

Based on Promise style calling, we can decompose the function into two parts. Next, let’s transform some of the code to transfer data:

  1. Complete the query code in getMemoList
// 获取备忘录列表
function getMemoList() {
  // 1. 获取数据库引用
  const db = wx.cloud.database()
  // 2. 找到集合获取数据
  return db.collection('memo').get()
}
  1. Render the query results in a list on the list page
 onShow() {
    getMemoList().then(res => {
      this.udpateList(res.data)
    })
  }

In this way, we successfully display the data from the database

image.png
Next, we will implement all methods on the cloud API.

View data details

We cannot use the index subscript here. Usually we use ID to query when interacting with the backend. Each piece of data will generate an ID field, and the field name is _id.

image.png
Then we need to change the parameters passed by the previous component and the fields obtained and the parameter fields before the page:
list.wxml code snippet, where data-id="{ {item._id}}" is the modified part

<view bindtap="toEdit" bindlongtap="del" data-id="{
   
   {item._id}}" class="list" wx:for="{
   
   {list}}">
      <view>
        <text class="list-title">{
   
   {item.title}}</text>
        <text class="list-date">{
   
   {item.date}} \n {
   
   {item.time}}</text>
      </view>
      <view class="list-content">{
   
   {item.content}}</view>
      <view class="line"></view>
    </view>

Get the id for page delivery

// 去编辑
  toEdit(event) {
    let id = event.currentTarget.dataset.id
    if (id) {
      // 从列表点击
      wx.navigateTo({
        url: '/pages/edit/edit?id=' + id,
      })
    } else {
      // 从新建按钮点击,省略相关代码
    }
  }

The query method is modified. Since querying by id is a very common method, the cloud API directly has a doc method to pass in the id to query:
getMemoInfo function code in memo.js

// 获取备忘录详情
function getMemoInfo(id) {
  // 1. 获取数据库引用
  const db = wx.cloud.database()
  // 2. 找到集合获取数据
  return db.collection('memo').doc(id).get()
}

Query method call:
onLoad function code in edit.js

onLoad: function (options) {
    if (options.id) {
      // 显示已有数据
      getMemoInfo(options.id).then(res=>{
        console.log(res)
        const item = res.data
        this.setData({
          title: item.title,
          content: item.content,
          nowDate: item.date,
          nowTime: item.time,
          id: options.id
        })
      })
    }
  }
Add memo data

New method modification:
addMemoInfo function in memo.js

// 新增备忘录信息
function addMemoInfo(data) {
   // 1. 获取数据库引用
   const db = wx.cloud.database()
   // 2. 找到集合获取数据
   return db.collection('memo').add({data})
}

Calling method:
Add a new logic code snippet to the save function in edit.js

// 新增逻辑
      addMemoInfo(data).then(res=>{
        console.log(res)
        wx.navigateBack()
      })

After the addition is successful, the ID information of the newly added data will be returned.

image.png
Then you can see the new data in the database.

image.png
We will find that the data added manually is different from the data added using the function added by the cloud API. This data has an additional "_openid" field. This _openid represents the unique identification of the current user. Each user's _openid represents this user in a small program. The _openid is different in different small programs.

Little knowledge: The applet also uses the _openid field to distinguish whether this data belongs to the current user. We can do an experiment. We adjusted the database permissions of the memo collection to "only the creator can read and write".

image.png
Then look at the data returned in the following list, only the data you added is the only one.

image.png

Modify memo data

Modification method modification:
updateMemoInfo function in memo.js.

// 修改备忘录信息
function updateMemoInfo(id, data) {
  // 1. 获取数据库引用
  const db = wx.cloud.database()
  // 2. 找到集合获取数据
  return db.collection('memo').doc(id).update({data})
}

The previous modification logic was to delete and then add "fake" modifications. This time we directly adopt the modification method.
The save function in edit.js modifies the logical code fragment

// 修改逻辑
      updateMemoInfo(this.data.id,data).then(res=>{
        console.log(res)
        wx.navigateBack()
      })

updated in the return result represents the number of successfully modified data

image.png

Delete memo data

Delete method modification:
deleteMemoInfo function in memo.js

// 删除备忘录信息
function deleteMemoInfo(id) {
  // 1. 获取数据库引用
  const db = wx.cloud.database()
  // 2. 找到集合获取数据
  return db.collection('memo').doc(id).remove()
}

Calling method:
del function in list.js

// 删除
  del(event) {
    let that = this
    let id = event.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content: '你确定删除?',
      success(res) {
        if (res.confirm) {
          const list = deleteMemoInfo(id).then(res=>{
            console.log(res)
            getMemoList().then(res => {
              that.udpateList(res.data)
            })
          })
        }
      }
    })
  }

What should be noted here is that after deletion, you need to call the query all data method to update the list.

image.png
The return value removed is the deleted quantity.

Summarize

In this section, we use the cloud API to operate the cloud database on the mini program and learn the following functions:

  • Use get() to query the database
  • Data was added using add()
  • Data modifications were made using update()
  • Data was deleted using remove()

Here we have completed using the cloud database to store memo data, and we will no longer have to worry about data loss in the future. So Ma Zai took this cloud data version of the memo to Ma Niu for use, and got Ma Niu's approval.

image.png

To learn more about how to get started quickly with small program cloud development, please pay attention to CRMEB

Guess you like

Origin blog.csdn.net/CRMEB/article/details/132066507
Recommended