Wechat applets cloud development

Start from 0 using applets cloud development


1.1. Initialization of the cloud development environment

// app.js
  onLaunch: function () {
    // The cloud development environment is initialized
    wx.cloud.init({
      env: 'cloud1-1gklnc7n550025ef' // Cloud development environment ID})},Copy the code

1.2. Add, delete, modify and check the database

  • The GET method queries data
  • Where Queries the data that meets the conditions
  • Doc Queries a single piece of data
  • The add method adds new data
  • The update method modifies data
  • Remove Deletes a single piece of data
// 1. Get the database reference
const db = wx.cloud.database()
// 2. Construct a query statement
The collection method gets a reference to a collection
The where method passes in an object, and the database returns a JSON document whose fields are equal to the specified values in the collection. The API also supports advanced query conditions (such as greater than, less than, in, etc.), as described in the documentation view support list
The get method triggers a network request to fetch data from the database
db.collection('books').where({
  publishInfo: {
    country: 'United States'
  }
}).get({
  success: function(res) {
  / / output [{" title ":" The Catcher in The Rye ",...}]
  console.log(res)
 }
})


// index.js

// Query operation

// The traditional way
			wx.cloud.database().collection('recommend_food')
			.get({
				success(res){
					console.log('Request successful',res)
				},
				fail(err){
					console.log('Request failed',err)
				}
			})

// es6
			wx.cloud.database().collection('recommend_food')
				.get().then(res= > {
					console.log('Request successful',res)
				},err= >{
					console.log('Request failed',err)
				})
Copy the code

1.3. The storage

Cloud development provides storage space and cloud download capability for uploading files to the cloud with permission management. Developers can use the cloud storage function through apis on the small program side and cloud function side.

// Let the user select an image
wx.chooseImage({
  success: chooseResult= > {
    // Upload the image to cloud storage space
    wx.cloud.uploadFile({
      // Specify the cloud path to upload
      cloudPath: 'my-photo.png'.// Specifies the applets temporary file path for the file to upload
      filePath: chooseResult.tempFilePaths[0].// Successful callback
      success: res= > {
        console.log('Upload successful', res)
      },
    })
  },
})
Copy the code

1.4. Cloud function

A cloud function is a piece of code that runs in the cloud and can be written in a development tool, uploaded and deployed with one click, without the need to manage a server. An API specifically for cloud function calls is provided within the applets. Developers can use the getWXContext method provided by WX-server-SDK in the cloud function to obtain the context of each call (appID, OpenID, etc.), and obtain the natural trusted user login state (OpenID) without maintaining complex authentication mechanism.

  1. Writing cloud functions

  2. One-click Deployment of cloud functions (cloud functions need to be redeployed after changes)

  3. Calling the cloud function

    // Cloud function entry file
    const cloud = require('wx-server-sdk')
    
    cloud.init()
    
    // Cloud function entry function
    exports.main = async (event, context) => {
      const wxContext = cloud.getWXContext()
    
      return {
        event,
        openid: wxContext.OPENID,
        appid: wxContext.APPID,
        unionid: wxContext.UNIONID,
      }
    }
    Copy the code
1.41. Initialize the environment of the cloud function
  1. Create a folder named Cloud that is the equivalent of Pages

  2. In project.config.json, set the cloud function to cloud.

    "cloudfunctionRoot": "/cloud"
    Copy the code
  3. The cloud folder icon appears as a cloud representing success

1.42. Cloud function calls
  1. Create the Node.js cloud function

  2. Write the cloud function entry function

    exports.main = async (event, context) => {
      return cloud.database().collection('recommend_food')
    			.get()
    }
    Copy the code
  3. Calling the cloud function

    // Cloud function call
    wx.cloud.callFunction({
    	name: 'getData',
    }).then(res= > {
    	console.log('succes',res)
    	this.setData({
    		openid: res.result.openid
    	})
    },err= > {
    	console.log('error',err)
    })
    Copy the code
1.43. Multiple cloud development environment issues
  1. Specify the cloud development environment you want to use in the cloud function

  2. Use the DYNAMIC_CURRENT_ENV constant

    cloud.init({
      env: cloud.DYNAMIC_CURRENT_ENV
    })
    Copy the code