Development of cloud

Developers can use cloud development to develop wechat mini programs and games, without building a server, you can use cloud capabilities.

Cloud development provides complete cloud support for developers, weakening the concepts of back-end and operation and maintenance. Without setting up servers, core business development can be carried out using API provided by the platform, enabling rapid launch and iteration. At the same time, this capability is mutually compatible with the cloud services already used by developers, rather than mutually exclusive.

Similar to Bmob backend cloud or knowing cloud

The emergence of cloud development, so that the development of small programs become more simple and convenient, developers can not buy to build a server, do not have to worry about the stability of the server and the installation of the database

Cloud development

In the wechat development tool, click “cloud development” directly, which will guide you to open. It should be noted that the cloud development ability is supported from base library 2.2.3

After cloud development is enabled, a cloud development environment is automatically obtained. Each environment is isolated from each other, and each environment contains independent database instances, storage space, cloud function configuration, and other resources. Each environment is identified by a unique environment ID. The environment created initially automatically becomes the default environment.

There is a free basic version

By default, you can have a maximum of two environments after cloud development is enabled. In real development, it is recommended that each formal environment be accompanied by a test environment

The database

Cloud development provides a JSON database (which can be understood as NoSQL database like MongoDB), which is a JSON format object. A database has multiple collections, equivalent to the tables of a relational database. There are multiple objects in the collection array, and each object is a record, equivalent to a row in a relational database. The database operation provides many apis, which are illustrated with simple examples

[{"id": 342166,
      "haspromotionTag": false."img": "http://p1.meituan.net/128.180/movie/740bd990e4af29d537ce324ec2cd08d6300433.jpg"."version": "v2d imax"."nm": "Unique"."preShow": false."sc": 8.9."globalReleased": true."wish": 125425,
      "star": "Chow Yun-fat, Aaron Kwok, Jingchu Zhang"."rt": "2018-09-30"."showInfo": "2,258 shows in 183 theaters today."."showst": 3."wishst": 0}, {"id": 1209159,
      "haspromotionTag": false."img": "http://p0.meituan.net/128.180/movie/4d9bedd239f41eaf08cd1c4297e4ec7d858156.jpg"."version": ""."nm": "Find you"."preShow": false."sc": 9,
      "globalReleased": true."wish": 66559,
      "star": "Yao Chen, Ma Yili, Yuan Wenkang"."rt": "2018-10-05"."showInfo": "1,039 in 182 theaters today."."showst": 3."wishst": 0}]Copy the code

storage

The base version offers five gigabytes of storage and can store files (pictures, videos…) Upload it to the storage space and manage it in the cloud. Direct use of small procedures provided by the upload and download interface, processing is very convenient.

Cloud function

Cloud function is to write back-end code, cloud function can operate database, operation storage, according to their own business needs to complete the implementation of back-end code. Cloud functions are deployed in the cloud, but we can write back-end cloud functions in the development tool, and then deploy to the cloud after completion, so to speak, all the logic is in a set of code.

My first cloud development applets

When creating a cloud development project, according to the official description, there is a QuickStart option in the wechat development tool, but I found that there is no QuickStart option. It may be the development tool version or other reasons.

Add data to the database

I copied some of the data from Cat’s Eye, and I’m going to dump it into a database developed by the small program cloud

As you can see, from the console, you can add data yourself, or you can dump it directly into a JSON file. I chose to call its API here to dump the cat’s eye JSON data

I first create a collection of movies and then call the initialization methods

app.js

. onLaunch:function () {
    wx.cloud.init()
}
...
Copy the code

To manipulate the database, I need to get the database reference, and I need to get the reference to the collection of movies I just created, which I’ll attach to the properties of my app because I need to call them on other pages

const app = getApp()
...
app.$db = wx.cloud.database()
app.$collect_movies = app.$db.collection('movies')...Copy the code

Finally, the added method is called

data.subjects.forEach(o => {
  app.$collect_movies.add({
    data: o
  })
})
Copy the code

There is now added data in the Cloud Development Console database

Show all movies

app.$collect_movies.where({
  _openid: 'ofgUd0Rb4w8E7Af40N46ExxozS5g'
}).get({
  success: function (res) {
    console.log('res', res)
    that.setData({
      movies: res.data
    })
  }
})
Copy the code
Queries specified movies by ID
app.$collect_movies.doc('W8Wf4t2AWotkhlzK').get({
    success: function (res) {
      console.log('res',res)
      that.setData({
        movie: res.data
      })
    }
})
Copy the code
Query movies with a score above 9
const _ = app.$db.command
app.$collect_movies.where({
    sc: _.gte(9)
}).get({
    success: function (res) {
      wx.hideLoading()
      that.setData({
        movies: res.data
      })
    }
})
Copy the code
Score more than 9 points or 0 points
const _ = app.$db.command
app.$collect_movies.where({
    sc: _.eq(0).or(_.gte(9))
}).get({
    success: function (res) {
      wx.hideLoading()
      that.setData({
        movies: res.data
      })
    }
})
Copy the code
Change the name of the lead actor
# confirm the change
const that = this
app.$collect_movies.doc(this.currentMovieId).update({
  data: {
    star: this.data.actor
  },
  success: function (res) {
    that.initUpdateData()
  }
})
Copy the code
Delete a movie
# delete
delAction(e) {
    const that = this
    const id = e.currentTarget.dataset.id
    app.$collect_movies.doc(id).remove({
      success: function (res) {
        that.initUpdateData()
      }
    })
}
Copy the code

File management

Upload images to the cloud storage system

Try uploading the photos of your phone’s album to the mini program cloud storage. You can directly use the API provided on the mini program side

wx.cloud.uploadFile({
  cloudPath: 'example.png'// Upload to cloud path filePath:' ', // applet temporary file path success: res => {// return fileID console.log(res.fileid)}, fail: console.error})Copy the code

If purely from the amount of code, than uploaded to Tencent’s own Tencent Cloud is simple, of course, than uploaded to ali Cloud, seven niuyun such a platform operation is simpler.

After a successful upload, the file ID is returned instead of the image URL. If you want to display an image or play a video, this file ID is also recognized by the widget image/ Video

 <image class="movie" mode="widthFix" src="{{ fileId }}" wx:if="{{ fileId }}"> </image>
Copy the code
upload() {
    const that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original'.'compressed'].sourceType: ['album'.'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths[0])
        wx.cloud.uploadFile({
          cloudPath: 'test/2.png', // upload to cloud filePath: tempFilePaths[0], // small program temporary filePath success: Log (res.fileid) that.setData({fileID: res.fileid})}, fail: console.error})}})}Copy the code

Download the file based on the file ID
downloadFile() {
  wx.cloud.downloadFile({
  fileID: 'cloud://ii-1853ca.6969-ii-1853ca/test/2.png', success: res => {// return temporary file path console.log('tempFilePath', res)
    // cloud://ii-1853ca.6969-ii-1853ca/test/2.png
    this.setData({
      downloadFileResult: res
    })
  },
  fail: err => {
    // handle error
  }
})
Copy the code

Exchange temporary network links based on file ID

You can exchange a temporary file network link based on the file ID, and the file link is valid for two hours

const that = this
wx.cloud.getTempFileURL({
    fileList: [this.data.fileId],
    success: res => {
      // https://6969-ii-1853ca-1253918415.tcb.qcloud.la/test/2.png
      that.setData({
        fileList: res.fileList
      })
    },
    fail: err => {
      // handle error
    }
})
Copy the code

Cloud function

How to play?

Cloud functions run in node.js

First locate the configuration file project.config.json in the applets project root directory and add a configuration that specifies the local existing directory as the local root directory for the cloud functions

  "cloudfunctionRoot": "./functions/".Copy the code

And the magic thing is that the icon becomes the “cloud directory icon.”

I created a new cloud function by right clicking the menu, where the file name is the name of the cloud function

Every time you create a cloud function, a popup window will appear asking you if you have a Node environment. After confirming, the terminal will automatically open and install dependencies, so every cloud function will look like this:

In index.js, this is the default

// cloud function entry file const cloud = require('wx-server-sdk'Cloud.init () // cloud function exports.main = async (event, context) => {}Copy the code
Create an additive cloud function

plus/

// cloud function entry file const cloud = require('wx-server-sdk'Cloud.init () // cloud function entry function // context object contains the call information and running state of this call // event refers to the event that triggers cloud function exports.main = async (event, context) => {return {
    sum: event.a + event.b
  }
}
Copy the code

Call plus cloud function in the small program side, the parameter name is easy to see, need not explain

wx.cloud.callFunction({
  name: 'plus',
  data: {
    a: 1,
    b: 2,
  },
  success: function (res) {
    console.log('plus', res.result) // 3
  },
  fail: console.error
})
Copy the code

An error occurs because the created cloud function is not uploaded and deployed to the cloud. How to deploy it? See below

After successful deployment, we went to the cloud console and found that the cloud function was already there

Go back to the applet, call the cloud function again, and find that it is ready, and get the expected value of 3

Get applets user information

The unique advantage of cloud function of cloud development lies in its seamless integration with wechat login authentication. When the small program side calls the cloud function, the openID of the user on the small program side will be injected into the input parameters of the cloud function. The developer does not need to verify the correctness of OpenID, because wechat has completed this part of authentication, and the developer can directly use the OpenID. Along with OpenId, the appID of the applet is injected into the cloud function

Defining cloud functions

// cloud function entry file const cloud = require('wx-server-sdk'Cloud.init () // cloud function exports.main = async (event, context) => {cloud.init() // cloud function exports.main = async (event, context) => {return event.userInfo
}
Copy the code

Calling the cloud function

wx.cloud.callFunction({
    name: 'userInfo',
    success: function (res) {
      console.log('userInfo', res.result)
        /*
          {
            appId:"wx8dae61dd0ef5c510",
            openId:"ofgUd0Rb4w8E7Af40N46ExxozS5g"
           }
        */
    },
    fail: console.error
})
Copy the code
Asynchronous cloud function
// cloud function entry file const cloud = require('wx-server-sdk'Cloud.init () // cloud function exports.main = async (event, context) => {cloud.init() // cloud function exports.main = async (event, context) => {return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(event.a + event.b)
    }, 3000)
  })
}
Copy the code

In cloud functions we can introduce third party dependencies to help us develop faster. The cloud functions run in Node.js, so we can use NPM to install third-party dependencies. For example, in addition to using the native HTTP interface provided by Node.js to initiate network requests in the cloud, we can also use a popular Node.js network request library request to initiate network requests more easily.

Note that dependencies are now not automatically installed in the cloud when uploading cloud functions. Developers need to install dependencies locally and upload them together.

Cloud functions operate databases
// cloud function entry file const cloud = require('wx-server-sdk'Cloud.init () const db = cloud.database() // cloud function exports.main = async (event, context) => {// Get movie set datareturn db.collection('movies').get()
}
Copy the code
Cloud functions call other cloud functions

Defining cloud functions

// cloud function entry file const cloud = require('wx-server-sdk'Cloud.init () // cloud function exports.main = async (event, context) => {cloud.init() // cloud function exports.main = async (event, context) => {return await cloud.callFunction({
    name: 'plus',
    data: {
      a: 1,
      b: 2,
    }
  })
}
Copy the code

Calling the cloud function

wx.cloud.callFunction({
  name: 'cloudFuncCallColundFunc',
  complete: res => {
    console.log('cloudFuncCallColundFunc', res)
  },
})
Copy the code
Cloud function logging, testing

You can see the call log of the called cloud function

You can directly test the written cloud function by passing in parameters and clicking the Run debug button

Summary of initial experience of cloud development

Cloud development about public beta in August, released in September, has now been quick in November, according to the official description, there are a lot of developers to get involved, as they did not anticipate, were also put forward a lot of fun point and small application of cloud development also can be said to be in water phase, there are many pits, later it will be better and perfect. Maturing can be a great solution, especially for startups.