Cloud development is a newly opened feature of wechat platform, providing developers with cloud services integrating servers, databases and resource storage. This article will use a small example to explore the relevant features of cloud development, based on the official documentation.

Cloud development official documentation

I. New cloud development projects

New project

After updating the wechat development assistant, select the cloud development template.

Project directory

The project directory is divided into two chunks: CloudFunctions and miniProgram. Miniprogram stores the same business codes and resources as normal development, while cloudfunctions stores the codes that can be uploaded to the cloud, which are called cloudfunctions in cloud development. Once the cloud development template is created, it comes with some examples to familiarize yourself with the API.

Ii. Console

After the update of wechat developer tools, there will be a console entrance in the toolbar. Click and the following panel will appear to check the relevant data.

An overview of

The overview screen, shown above, shows statistics on cloud resource usage under the cloud development project.

User management

All users who have visited cloud projects will have access records under user management. The premise is that the small program sets traceUser:true in app.js, indicating that user information is allowed to be recorded.

    wx.cloud.init({
        env:'... '.traceUser: true,})Copy the code

The database

Database is one of the most commonly used functions in the console. Under this interface, you can quickly establish data sets, which can be understood as data tables. New collections can be created in the console, and records can be added in three ways: console manual addition, file import, and API calls. Calling the API automatically inserts the user _openID in each record.

Storage management

Storage management can save files uploaded by the small program side. You can upload files by calling API. The upload name and path need to be defined by yourself.

Cloud function

The cloudfunction manages the uploaded functions in Cloudfunctions, debugging them, and viewing call logs.

There are two ways to add cloud functions, visual add and IDE add. The cloud functions added visually are directly uploaded to the cloud, and IDE can only be called after being uploaded and deployed. To delete cloud functions, synchronize the list of cloud functions in the IDE after the console is deleted.

Statistical analysis

Statistical analysis of calls to cloud services provides specific data.

Three, environment configuration

The API automatically inserts user _openID into each record.

The project initialization needs to be configured in app.js, and the env is the self-configured environment ID.

    wx.cloud.init({
        env:'mina-cloud-test001'
    })
Copy the code

Four, practical application

In this example, the above book information is a practical application to achieve the basic functions of adding, deleting, modifying and searching book information, as well as uploading and deleting pictures.

Reading database data

Start by calling wx.cloud.database(); Retrieves all collections of the database, and then retrieves data by querying specific collections.

    const db = wx.cloud.database();
    const _ = db.command;
    
    db.collection('bookList').get().then(res= > {
        console.log('get', res)
        self.setData({
            bookList: res.data
        });
    })
Copy the code

Increase the data

    const db = wx.cloud.database();
    const _ = db.command;
    
    db.collection('bookList').add({
        data: {
          bookMes: self.data.bookMes
        }
    }).then(res= > {
        console.log(res)         
    })
Copy the code

Delete the data

    db.collection('bookList').doc(id).remove().then(res= > {
        console.log(res)
        wx.showToast({
            title: 'Deleted successfully! ',
        })
        self.getBook();
        }).catch(err= > {
            console.log('err', res)
        })
    })
Copy the code

Increase the data

    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)
        })
    })
Copy the code

Change the data

    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)
Copy the code

Query data & call cloud functions

The cloud function is used as an example to query data

Each cloud function that needs to call the cloud development API must use wX-server-SDK. When a new cloud function is created, the project will prompt you whether to use the dependency. If yes, the WX-server-SDK will be automatically installed. The event parameter in the function represents the parameter passed by the applet side. Besides, the default contains userInfo, which can be used for user authentication.

	// Cloud function entry file
    const cloud = require('wx-server-sdk')
    cloud.init()
    const db = cloud.database()
    const _ = db.command
    
    // Cloud function entry
    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
        }
	  })
	}
Copy the code

Name is the name of the cloud function folder. Data stores the parameters passed to the cloud function, which is obtained by event:

    wx.cloud.callFunction({
        name: 'searchBook'.// The parameters passed to the cloud function
        data: {
            bookMes: self.data.bookMes
        }
    }).then(res= > {
        console.log('search',res.result.data)
        self.setData({
            bookList:res.result.data
        })
    })
Copy the code

The API usage in this article is only an example. In fact, the API on the server side is richer and more functional than the API on the small program side. It is recommended to store design files and add, delete, modify and check the database in the cloud function.

To upload pictures

To upload an image, call the filePath parameter returned by wx.chooseImage, and then define cloudPath, the address to upload to the cloud.

    choose() {
        let self = this
        wx.chooseImage({
            count: 1./ / the default 9
            sizeType: ['original'.'compressed'].// You can specify whether the image is original or compressed. By default, both are available
            sourceType: ['album'.'camera'].// You can specify whether the source is photo album or camera, and default is both
            success: function (res) {
            // console.log(res.tempFilePaths[0])
            // Returns the list of local file paths for the selected photo. TempFilePath can display the image as the SRC attribute of the IMG tag
                self.setData({
                    bookPic: res.tempFilePaths[0})}}, upload(){let self = this
        const filePath = self.data.bookPic
        let myDate = new Date(a);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)
        })
    }
Copy the code

Delete the picture

You can query a specific fileId to delete an image or other file. You can use the fileId to delete the image or other file.

    wx.cloud.deleteFile({
        fileList: [fileId],
        success: res= > {
            console.log('delete', res.fileList)
        },
        fail: err= > {
            console.log('deleteE', err)
        }
    })
Copy the code

Five, discover the existing problems

In the process of writing practical examples, I also found some problems, because the function of cloud development is not very perfect since it was not long ago. I summarized some small problems found:

  1. The database does not support fuzzy query
  2. Database collections cannot be associated
  3. If cloudPath is the same as the previous image, the result is successfully returned, but it is actually replaced with the previous image
  4. The globalData definition method has changed and cannot be defined at the same level as onLaunch.

Six, the concluding

About cloud development, the official documentation gives more detailed instructions, careful reading of the documentation can be faster to achieve a hands-on application. However, due to the limitations of its current functions, it is not suitable for the development of complex corporate businesses, but for small personal businesses. If there are any inaccuracies in the above article, please kindly point out and revise, thank you! ヾ(= · ω · =)o