小試小程序雲開發(小結)

這篇文章主要介紹了小試小程序雲開發(小結),小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

微信小程序剛出沒多久時,曾經上手寫過demo,但開發體驗比較差,所以一直沒怎麼關注。不過自從諸多適配方案出爐,以及雲端的開通,覺得還是有必要上手體驗一番的,於是爲我的技術博客也寫了個小程序版。

原生開發我是不想再試了,那就選一種適配方案,目前比較知名的有基於vue的 mpvue,umi-app,基於react 的 taro,以及TX團體出的全新框架 wepy。個人對 react 的好感 以及 taro 框架的走向成熟,促使我選擇了 taro。

雲端開發就是將普通小程序的傳統後端切換爲微信提供的 輕量級雲端。而這個雲端服務部分的開發其實是針對前端開發的,前端工程師很容易就能全棧開發出一整個小程序。但是這種輕量級解決方案也只是針對業務簡單的項目,因爲公共平臺肯定有各種限制,它的出現只是讓我們多了一個選擇方案而已。

接着進入主題,項目大體目錄結構如下

client #前端目錄
├── config #配置
├── dist #輸出
├── src #源目錄
└── index.html #入口文件
cloud #雲目錄
├── dao #數據庫操作函數集合
├── login #登錄雲函數
└── ... #其他

前端

小程序的前端部分,想必不用過多講解,因爲這都是前端的基本功。就以首頁爲樣例,使用了typeScript,主要功能是分頁加載數據,調用微信提供的觸發到達底部的api-onReachBottom即可。

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

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() {
  this.getList();
  this.getLogin();
 }

 getDbFn(fn, param) {
  return Taro.cloud.callFunction({
   name: "dao",
   data: { fn, param }
  });
 }

 onReachBottom() {
  this.getList();
 }
 
 getList() {
  const { size, page, total, loading } = this.state;
  if (loading) return;
  Taro.showLoading({ title: 'loading', });
  if (total >= 0 && size * page >= total) return;
  this.setState({ loading: true });
  this.getDbFn("getList", { size, page: page + 1 }).then(res => {
   Taro.hideLoading();
   const total = res.result.total;
   const list = this.state.list.concat(res.result.list);
   this.setState({ loading: false, page: page + 1, total, list });
  }).catch(err => {
   Taro.hideLoading();
   this.setState({ loading: false });
  });
 }

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

與普通小程序不同的地方就是調用雲端,雲函數調用如官方樣例所示

getLogin(){
  Taro.cloud.callFunction({
   name: "login",
   data: {}
  }).then(res => {
   this.setState({ context: res.result });
  }).catch(err=>{
  });
}

雲端

雲端數據庫是個文檔型,操作風格與mongodb如出一轍,格式自然是json。最有用的還是操作數據庫的部分,操作方法都已經 Promise 化,調用還是比較方便的。具體內容請查看文檔: 小程序雲開發

//數據庫引用
const db = wx.cloud.database()
//獲取數據集合
const todos = db.collection('todos')

//獲取記錄數
todos.count();
//條件查找
todos.where({done: false,progress: 50}).get()

//插入
todos.add({data: {content:'11',time:new Date()}},success:(res){});

//更新
todos.doc('todo').update({ data: { done: true}},success:(res){});

//刪除
todos.where({done:true}).remove();

//分頁查找
todos.orderBy('time','desc')
  .skip(start)
  .limit(size)
  .get();

雲函數

調用雲端的方式就要使用雲函數,就以下面數據庫操作庫爲例

// 雲函數入口文件
const cloud = require("wx-server-sdk");
cloud.init();

// 雲函數入口函數
exports.main = async (event, context) => {
  const { fn, param } = event;
  return dao[fn](param);
};
// 調用數據庫
const db = cloud.database();
// 表
const posts = db.collection("posts");
const tags = db.collection("tags");
const dao = {
  async getList({ page = 1, size = 10 }) {
    const start = (page - 1) * size;
    try {
      const { total } = await posts.count();
      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 posts.doc(id).get();
  },
  async getTagList({ tag }) {
    try{
      const { data } = await tags.where({ name: tag }).get();
      if(!data.length){ 
        return {
          code:0,
          list:[],
          message: "success"
        };
      } 
      const list = data[0].list.sort((a,b) => b.num - a.num);
      return {
        code:0,
        list:list,
        message: "success"
      };
    } catch(err){
      return {
        code: -1,
        list:[],
        err: err,
        message: "error"
      };
    }
  }
}

將操作數據庫的所有云函數合併成一個文件,將雲函數入口封裝一下,即把函數名字和參數都做爲參數

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

對應前端部分也封裝出一個調用數據庫的方法

 getDbFn(fn, param) {
  return Taro.cloud.callFunction({
   name: "dao",
   data: { fn, param }
  });
 }

雲端部分開發完之後,在微信開發者工具裏面上傳雲端代碼即可,而其餘部分的流程和普通小程序一樣,這裏也不再介紹。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章