评论

几行代码封装,让小程序云函数变为真正云函数,开发体验直接起飞

真正云函数:服务器编写方法,客户端直接调用方法,不再需要传输json的接口。思路更清晰、代码更精简。

一、目标

像调用普通方法那样使用云函数。

二、效果演示(以电影查询小程序为例)

三、小程序使用流程

  1. 核心封装代码:在 utils 目录创建 cloudFunction.js 文件
/**
 * 导入云函数
 * @param {String} name 云函数名
 * @returns {Promise} 返回云函数处理结果
 */
globalThis.importCloudFunction = function (name) {
  return new Proxy(
    {},
    {
      get(target, prop) {
        return async function (...args) {
          let res = await wx.cloud.callFunction({
            name,
            data: {
              method: prop,
              params: args,
            },
          });
          return res.result;
        };
      },
    }
  );
};
  1. 导入封装代码:在 app.js 引入 cloudFunction.js
// app.js
import "./utils/cloudFunction.js";
  1. 前端使用:在需要用的地方导入方法
// 某个页面.js
const { method1,method2,method3 } = importCloudFunction("函数名");
​
Page({
  data: {},
  onLoad() {
      method1();
  },
});

四、云函数使用流程

  1. index.js 封装的代码
exports.main = async (event, context) => {
  globalThis.originInfo = { event, context };
  const { method, params = [] } = event || {};
  if (method) {
    return require("./handle")[method](...params);
  }
  return { ...originInfo };
};
  1. 在同级目录创建handle.js
module.exports = {
    method1(a,b){
        return a;
    },
    method2(a,b){
        return b;
    },
}

五、电影示例逻辑源代码片段

https://developers.weixin.qq.com/s/Az8Mo3m47pXY

最后一次编辑于  01-09  
点赞 1
收藏
评论
登录 后发表内容