Small program cloud development strategy to solve the most difficult problems

Keywords: Javascript Database Attribute JSON TypeScript

background

Recently, the small program is very popular. According to the requirements of the company's business development, several small programs have been developed and maintained. The small programs developed by the company are all interfaces provided by the back-end. The development is tedious and complex. Until the small programs appear in the cloud development, after carefully reading the documents, I am very happy. So I started to develop my first small program.

Analysis

Cloud development provides developers with complete native cloud support and Wechat service support, weakens the concept of back-end and operation and maintenance. Without the need to build servers, we can use API provided by the platform to develop core business to achieve rapid online and iteration. At the same time, this capability is compatible with the cloud services already used by developers and is not mutually exclusive.

advantage

  • No self-built server, database, self-built storage and CDN
  • The database model is very simple. It's a json-style object format.
  • Calling the cloud function on the server side automatically obtains openid, and there is no more tedious authorization login process. As long as you enter the small program, it will be the login state. It's a good experience.
  • Rapid development, only need front-end can complete all the development work

Problems to be solved

Database switching problem

People who have used cloud development have found that switching database environment in cloud development is the most headache. If switching by hand is easy to make mistakes, they accidentally modify online database data in the current environment.

Until the official problem of this function is solved.

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

I use the service-side cloud development function. Why do I make this judgement? Because ENV ='local'in the development tool, I make this judgement to ensure that the test environment database is used in the development tool.

Using taro multi-terminal development framework and web pack, the current code development environment can also be distinguished by process.env.NODE_ENV value.

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

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

Definition of database field

Because JS is a weakly typed language, it can't define variable types statically like typescript, so the number and type of fields added to the database can't be controlled.

I don't want to use typescript. Can I do this? I can use the superstruct library to do this.

See the following code for a detailed use case

The problem of too many function files

Examples of official and other tutorials are a file corresponding to a cloud function. Through development experience, I find that this is not good. When the project has multiple tables, it is really difficult to find a function file.
We can write all the add, delete and modify functions of a table into a file.

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

{
  "dependencies": {
    "wx-server-sdk": "latest",
    "superstruct": "latest"
  }
}

The following code is a complete example of a cloud function

const cloud = require('wx-server-sdk');
const { struct, superstruct } = require('superstruct');
cloud.init();
//Cell information
const Model = () => {
  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', //Building unit number
          doorNumber: 'string', //Door number
          communityId: 'string', //Community id
          _openid: 'string' //User id
          //IsDefault:'boolean'// 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 is supported' };
      }
      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 determine whether the mobile phone number has been modified or not, change the data directly without modification, and modify to determine whether there is this data in the library.
    async update(data) {
      //Operation of updating tables
    },
    //Delete shop with specified id
    async remove({ _id, _openid }) {
      //Delete tables
    },
    /**
     * Getter List
     * @param {*} option {category Category, pagenum page number}
     */
    async getList({ _openid }) {
      const shopList = await collection
        .where({
          _openid
        })
        .get();

      return shopList;
    }
  };
};

exports.main = async (event, context) => {
  const { func, data } = event;
  const { ENV, OPENID } = cloud.getWXContext();
  // Update the default configuration and 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 = await Model()[func]({ ...data, _openid: OPENID });
  return {
    ENV,
    data: res
  };
};

Function usage

wx.cloud.callFunction({
      'address', //Cloud function file name
      data: {
        func: 'add', //The Method Defined in Cloud Function
        data: {} //Data to be uploaded
      }
    });

Files such as pictures and videos

Open the cloud development console directly and choose to store and upload files directly. Copy the url address and put it in the code.

Sweep code to experience my little program:

Posted by HGeneAnthony on Sun, 29 Sep 2019 02:27:06 -0700