SoFunction
Updated on 2025-04-07

Small trial mini program cloud development (summary)

When the WeChat mini program first appeared, I used to write a demo, but the development experience was relatively poor, so I haven't paid much attention to it. However, since many adaptation solutions were released and the cloud was launched, I felt it was necessary to get started and experience it, so I also wrote a mini program version for my technical blog.

I don’t want to try native development anymore, so I choose an adaptation solution. Currently, the more well-known ones include vue-based mpvue, umi-app, react-based taro, and a new framework wepy created by the TX group. My personal preference for react and the maturity of the taro framework prompted me to choose taro.

Cloud development is to switch the traditional backend of ordinary mini programs to the lightweight cloud provided by WeChat. The development of this cloud service part is actually for front-end development, and front-end engineers can easily develop a whole mini program on the full stack. However, this lightweight solution is only for simple business projects, because public platforms must have various restrictions, and its emergence only gives us an additional option.

Then enter the topic, the general directory structure of the project is as follows

client #Front-end directory├── config #Configuration├── dist #Output├── src #Source Directory└──  #Entry Filecloud #Cloud Directory├── dao #Database operation function collection├── login #Login cloud function└── ... #other

front end

I believe there is no need to explain too much about the front-end part of the mini program, because these are all basic skills of the front-end. Take the homepage as an example and use typeScript. The main function is to load data on pages and call the trigger provided by WeChat to reach the bottom api-onReachBottom.

import Taro, { Component, Config } from "@tarojs/taro";
import { View, Text, Navigator } from "@tarojs/components";
import "./";

interface IState {
 loading: boolean;
 size: number;
 page: number;
 total: number;
 list: Array<{ _id: string; summary: object }>;
 context:object;
}
export default class Index extends Component<{}, IState> {
 state = {
  loading: false,
  size: 10,
  page: 0,
  total: -1,
  list: [],
  context:{}
 };
 config: Config = {
  navigationBarTitleText: "Jeff's Blog",
  onReachBottomDistance: 50
 };

 componentWillMount() {
  ();
  ();
 }

 getDbFn(fn, param) {
  return ({
   name: "dao",
   data: { fn, param }
  });
 }

 onReachBottom() {
  ();
 }
 
 getList() {
  const { size, page, total, loading } = ;
  if (loading) return;
  ({ title: 'loading', });
  if (total >= 0 && size * page >= total) return;
  ({ loading: true });
  ("getList", { size, page: page + 1 }).then(res => {
   ();
   const total = ;
   const list = ();
   ({ loading: false, page: page + 1, total, list });
  }).catch(err => {
   ();
   ({ loading: false });
  });
 }

 onShareAppMessage (res) {
  return {
   title: "Jeff's Blog",
   path: '/pages/index/index'
  }
 }
 
 render() {
  return (
   <View className='container'>
    {(l => (
     <View className='item' key={l._id}>
      <Navigator url={'/pages/post/post?id=' + l._id}>
       <Image className='banner' mode='widthFix' src={} />
       <View className='title'>{}</View>
      </Navigator>
      <View className='sub-title'>
       {(t => (
        <Navigator className='tag' url={'/pages/list/list?tag=' + t}> {t} </Navigator>
       ))}
       <Text className='time'>{}</Text>
      </View>
     </View>
    ))}
   </View>
  );
 }
}

The difference between ordinary mini programs is to call the cloud, and cloud function calls are shown in the official example.

getLogin(){
  ({
   name: "login",
   data: {}
  }).then(res => {
   ({ context:  });
  }).catch(err=>{
  });
}

Cloud

Cloud database is a document type, and its operation style is exactly the same as mongodb, and the format is naturally json. The most useful part is to operate the database. The operation methods have been promised, so calling is quite convenient. For specific content, please check the document:Mini Program Cloud Development

//Database referenceconst db = ()
//Get the data collectionconst todos = ('todos')

//Get the number of records();
//Condition search({done: false,progress: 50}).get()

//insert({data: {content:'11',time:new Date()}},success:(res){});

//renew('todo').update({ data: { done: true}},success:(res){});

//delete({done:true}).remove();

//Pagination search('time','desc')
  .skip(start)
  .limit(size)
  .get();

Cloud functions

To call the cloud, you need to use cloud functions. Take the following database operation library as an example

// Cloud function entry fileconst cloud = require("wx-server-sdk");
();

// Cloud function entry function = async (event, context) =&gt; {
  const { fn, param } = event;
  return dao[fn](param);
};
// Call the databaseconst db = ();
// surfaceconst posts = ("posts");
const tags = ("tags");
const dao = {
  async getList({ page = 1, size = 10 }) {
    const start = (page - 1) * size;
    try {
      const { total } = await ();
      const { data } = await posts
        .field({ summary: true })
        .orderBy('num','desc')
        .skip(start)
        .limit(size)
        .get();
      return {
        code: 0,
        list: data,
        total,
        message: "sucess"
      };
    } catch (err) {
      return {
        code: -1,
        list: [],
        total: -1,
        err: err,
        message: "error"
      };
    }
  },
  getPost({ id }) {
    return (id).get();
  },
  async getTagList({ tag }) {
    try{
      const { data } = await ({ name: tag }).get();
      if(!){ 
        return {
          code:0,
          list:[],
          message: "success"
        };
      } 
      const list = data[0].((a,b) =&gt;  - );
      return {
        code:0,
        list:list,
        message: "success"
      };
    } catch(err){
      return {
        code: -1,
        list:[],
        err: err,
        message: "error"
      };
    }
  }
}

Merge all cloud functions that operate the database into a file, encapsulate the cloud function entry, that is, use the function name and parameters as parameters

 = async (event, context) => {
  const { fn, param } = event;
  return dao[fn](param);
};

The corresponding front-end part also encapsulates a method to call the database

 getDbFn(fn, param) {
  return ({
   name: "dao",
   data: { fn, param }
  });
 }

After the cloud part is developed, just upload the cloud code in the WeChat developer tool, and the process of the rest is the same as that of ordinary mini programs, and it will not be introduced here.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.