background

Small program recently very fire, should be the company’s business development requirements, development and maintenance for a few small programs, company developed small programs are provided by the backend interface, development cumbersome and complex, until the cloud in the small program development, after a careful reading documents, pleased, so I set out to develop the oneself first small programs

  • Small program cloud development tutorial address point I view >>

Analysis of the

Cloud development for developers to provide complete primary support and the clouds WeChat service support, and weaken the back-end and operational concepts, do not need to set up the server, use the API provided by the platform in terms of core business development, can be realized fast on-line and iteration, this ability at the same time, with the developers are already using cloud services compatible with each other, are not mutually exclusive.

advantage

  • No need to build your own server, database, storage and CDN
  • The database model is simple, just an object format in json form
  • Call the server cloud function to automatically obtain OpenID, no longer cumbersome authorization login process, as long as enter the small program is login state, the experience is really good
  • Development is fast, and all you need is the front end to do all the development

Problems that need to be solved

Database switchover problem

People who have used cloud development have found that cloud development switching database environment is the most headache, if manual switching is easy to mistake, accidentally modify online database data in the current environment

Until the official issue of this function is solved

cloud.updateConfig({
    env: ENV === 'local' ? 'dev-aqijb' : ENV
  });
Copy the code

ENV = ‘local’ ENV = ‘local’ ENV = ‘local

Using the Taro multi-endpoint development framework, with the help of Webpack, you can also differentiate the current code development environment by the value process.env.node_env

await Taro.cloud.init({
        env: `${process.env.NODE_ENV === 'development' ? 'dev-aqijb' : 'pro-hljv7'}`
        /* env: 'pro-hljv7' */
      });
Copy the code

This ensures that the development environment and the online environment can use the database of the corresponding environment

Database field definition problem

Because JS is a weakly typed language and cannot statically define variable types as typescript does, the number and type of fields added to the database cannot be controlled

I don’t want to use typescript, so I wonder if I can do this with the superstruct library

  • Superstruct git git

See the code below for detailed use cases

Problem with too many function files

The official and other tutorial examples are all one file for one cloud function, which I have found is not good through development experience. When the project has multiple tables, it is really difficult to find a function file. We can write all the add, delete, change and check functions of a table into one file

Tutorial: First introduce superstruct in package.json in each cloud function file

{
  "dependencies": {
    "wx-server-sdk": "latest"."superstruct": "latest"}}Copy the code

The following code is a complete example of a cloud function

const cloud = require('wx-server-sdk');
const { struct, superstruct } = require('superstruct');
cloud.init();
// Community information
const Model = (a)= > {
  const db = cloud.database();
  const _ = db.command;
  const collection = db.collection('address');
  return {
    async add(data) {
      try {
        data = struct({
          name: 'string'./ / name
          phone: 'string'.unit: 'number'.// Flat number
          doorNumber: 'string'./ / door
          communityId: 'string'.//小区id
          _openid: 'string' // User ID
          //isDefault: 'Boolean' // Whether the default address
        })(data);
      } catch (e) {
        const { path, value, type } = e;
        const key = path[0];

        if (value === undefined) {
          const error = new Error(`${key}_required`);
          error.attribute = key;
          throw error;
        }

        if (type === undefined) {
          const error = new Error(`attribute_${key}_unknown`);
          error.attribute = key;
          throw error;
        }
        const error = new Error(`${key}_invalid`);
        error.attribute = key;
        error.value = value;
        throw error;
      }
      let res = await this.getList({ _openid: data._openid });
      if (res.data.length >= 1) {
        return { msg: 'Currently only one address can be saved' };
      }
      res = await collection.add({
        data,
        createTime: db.serverDate(),
        updateTime: db.serverDate()
      });
      return res;
    },
    async getAdressById({ _openid, _id }) {
      const user = await collection
        .where({
          _openid,
          _id: _.eq(_id)
        })
        .get();
      return user;
    },
    // Update the specified id to check whether the mobile phone number has been modified or not
    async update(data) {
      // Update the table operation
    },
    // Delete the specified shop
    async remove({ _id, _openid }) {
      // Delete table operation
    },
    @param {*} option {category category, pagenum page number} */
    async getList({ _openid }) {
      const shopList = await collection
        .where({
          _openid
        })
        .get();

      returnshopList; }}; }; exports.main =async (event, context) => {
  const { func, data } = event;
  const { ENV, OPENID } = cloud.getWXContext();
  // Update the default Settings to set the default access environment to the current cloud function environment
  console.log('ENV', ENV);
  cloud.updateConfig({
    env: ENV === 'local' ? 'dev-aqijb' : ENV
  });
  let res = awaitModel()[func]({ ... data,_openid: OPENID });
  return {
    ENV,
    data: res
  };
};

Copy the code

Function usage

wx.cloud.callFunction({
      'address'.// Cloud function file name
      data: {
        func: 'add'.// The method defined in the cloud function
        data: {} // Data to be uploaded}});Copy the code

Pictures, videos and other files

Directly open the cloud development console select storage directly upload files, copy the URL address can be put into the code to use

Scan code to experience my small program: