WeChat applet - cloud function operation database to achieve login

When developing WeChat applets, using the traditional method of operating cloud databases has many disadvantages, such as code redundancy, which is not easy to maintain and modify, so it is now based on cloud functions to operate databases or other logic. It just so happens that I am working on a WeChat applet template that integrates shopping malls, garbage classification, and background systems. Through this case, let's learn about cloud functions. It is also convenient for me to copy directly in the future.

Tools needed:

1、node.js

2、tcb-router

By default, everyone will know the basic knowledge of node.js and will not say more

Open the template generated by the WeChat applet point cloud development, right-click cloudfunctions to create a new node.js cloud function function called db (meaning that the functions that operate the database are all here), after the creation is completed, the system will automatically generate a template, right-click db in the external Terminal window opens

Install tcb-router: npm install --save tcb-router

After the installation is complete, open the package.json of db, and you will see the following proof that the installation is successful

Code required:

const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router');
cloud.init({
  env: "dd-aqou2"
})
let db = cloud.database()
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let {
    APPID,
    OPENID
  } = wxContext
  const app = new TcbRouter({
    event
  })
  app.use(async (ctx, next) => {
    ctx.data = {};
    await next(); // 执行下一中间件
  });
  return app.serve();
}

In this way, the basic framework is built, and the login logic is written next. The api of the small program wx. The unique identifier of the user is openid. If the database has this openid, the user information will be updated, and if not, a new user will be created. When using tcb-router, I encountered a small problem, that is, the value cannot be assigned with other names, so I always use ctx.data.xxx to name the return value. First look at the renderings:

 

 Other buttons cannot be clicked when not logged in:

 Next, let's look at the logic of the cloud function:

 //  用户登录
  app.router("login", async (ctx, next) => {
    let {
      userInfo
    } = event
    //  连接数据库user
    let user = db.collection('user')
    let {
      total
    } = await user.where({
      OPENID: OPENID
    }).count()
    if (total) {
      await user.where({
          OPENID: OPENID
        })
        .update({
          data: userInfo
        })
    } else {
      await user.add({
        data: {
          nickName: userInfo.nickName,
          gender: userInfo.gender,
          avatarUrl: userInfo.avatarUrl,
          OPENID: OPENID,
          integral: 0, //总积分
          signTotal: 0, //连续签到天数
          signday: [] //签到日期
        }
      })
    }
    let {
      data
    } = await user.where({
      OPENID: OPENID
    }).get()
    ctx.data.rank = await user.orderBy('integral', 'desc').get()
    ctx.body = {
      code: 0,
      msg: "添加成功",
      userInfo: data[0],
      rank: ctx.data.rank
    }
    return
  });

Then we call the cloud function on the applet side (don’t forget to deploy the cloud function, right click on the db to upload and deploy, and install dependencies on the cloud)

Find the login button event

    /**
     * 获取用户信息
     */
    handleGetUserInfo(e) {
        wx.getUserProfile({
            desc: '用于完善个人资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
            success: (res) => {
                this.setData({
                    cloudID: res.cloudID,
                })
                wx.cloud.callFunction({
                    // 要调用的云函数名称
                    name: "db",
                    // 传递给云函数的参数
                    data: {
                        $url: "login", // 要调用的路由的路径,传入准确路径或者通配符*
                        userInfo: res.userInfo,
                    },
                    success: (res) => {
                        this.setData({
                            userInfo: res.result.userInfo
                        })
                        this.getRank(res.result.rank.data)
                    },
                });
            },
            fail: (res) => {}
        })
    },

Because I mainly focus on the front end, and the knowledge of the back end is not solid, so I put the logic of the ranking on the front end

  /**
     * 获取排名
     */
    getRank(arr) {
        for (let i = 0; i < arr.length; i++) {
            if (this.data.userInfo.OPENID === arr[i].OPENID)
                this.setData({
                    rank: i + 1
                })
        }
    }

Guess you like

Origin blog.csdn.net/yinzisang/article/details/122739217