Raiders small cloud development program to address the most difficult issues

background

Recently a very small program of fire, should the company's business development requirements, development and maintenance of several small programs, developed small programs are provided by the back-end interface development cumbersome and complex, until there was a small cloud development program, carefully study after the document, delight, so I set out to develop my first applet

analysis

Cloud development to provide complete for developers of native cloud support and micro-channel service support, weakening the back-end maintenance concept and operation, without the need to build a server, API using the platform provided by the core business development, we can achieve rapid on-line and iteration, and this capability , with the cloud service developers already use compatible with each other, they are not mutually exclusive.

Advantage

  • You do not need self-built servers, databases, no self-built storage and CDN
  • Database model is very simple, it is a form of json object format
  • Call the cloud server function automatically get openid, no cumbersome authorization process of landing, just go to a small program that landed state, really good experience
  • Rapid development, we need only be able to get all the front-end development work

issues that need resolving

Database switch problem

Used cloud development people are finding cloud development environment to switch database is the most troublesome, if the manual switch easily go wrong, accidentally modify the online database data in the current environment

Until an official function problems will be solved

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

I am using a server-side cloud development capabilities, why should this judgment, because the development tools ENV = 'local', so such a judgment, to ensure the development tools used in a test environment database

Use taro multiport development framework, by means of WebPACK, you may also be distinguished by the current code development environment value process.env.NODE_ENV

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

This ensures that the environment and development environment can be used online database corresponding to the ambient

Definition of database fields

Because JS is a weakly typed language, not as a static variable type is defined as the typescript, so adding to the number of fields and field types of databases can not control

I do not want typescript, can achieve this function it can be used to achieve this function library superstruct

For more use cases see below Code

Too many function file problem

Official tutorials and examples of others is a cloud file corresponds to a function, through the development of the experience I have found this is not good, when the project has multiple tables, really hard to find a file function
that we can be a table CRUD functions all written to a file

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

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

The following code is an example of a function of a complete cloud

const cloud = require('wx-server-sdk');
const { struct, superstruct } = require('superstruct');
cloud.init();
//小区信息
const Model = () => {
  const db = cloud.database();
  const _ = db.command;
  const collection = db.collection('address');
  return {
    async add(data) {
      try {
        data = struct({
          name: 'string', //名字
          phone: 'string',
          unit: 'number', //楼单元号
          doorNumber: 'string', //门号
          communityId: 'string', //小区id
          _openid: 'string' //用户的id
          //isDefault: 'boolean' //是否默认地址
        })(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: '当前只支持保存一个地址' };
      }
      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;
    },
    //更新指定的id 先判断手机号修改没,没修改直接就改数据,修改过判断一下库中有没有这条数据
    async update(data) {
      //更新表的操作
    },
    //删除指定id的shop
    async remove({ _id, _openid }) {
      //删除表的操作
    },
    /**
     * 获取商列表
     * @param {*} option {category 类别, pagenum 页码}
     */
    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();
  // 更新默认配置,将默认访问环境设为当前云函数所在环境
  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 use

wx.cloud.callFunction({
      'address', //云函数文件名
      data: {
        func: 'add', //云函数中定义的方法
        data: {} //需要上传的数据
      }
    });

Pictures and video files

Direct the development of open cloud storage console select direct upload files, you can copy the url address into the code used

Scan code to experience my little program:
Garbage classification

Guess you like

Origin www.cnblogs.com/chengfeng6/p/11611549.html