Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Cloud Development Cloud function routing tcb-router


May 22, 2021 Mini Program Cloud Development Advanced



tcb-router is a lightweight class routing library based on Nodejs koa-style cloud development cloud functions that can be used to optimize the processing logic when the front end (small terminal) calls cloud functions on the service side. We can use it to integrate several cloud functions with similar functions in a cloud function, such as addition and deletion of a collection, or we can integrate some fragmented functions of the back end into a cloud function for centralized management, etc.

First, tcb-router quick start

tcb-router is mainly used for processing logic when calling cloud functions on a small terminal, where we need to pass in the name of the cloud function to be called in name and the path to the route to be called in data, and app.router is used in the cloud side to write the processing function for the corresponding route.

Using developer tools, create a cloud function, such as a router, and then add the dependency of the latest version of tcb-router latest latest at package.json and install it with npm install:

  1. "dependencies": {
  2. "wx-server-sdk":"latest",
  3. "tcb-router": "latest"
  4. }

Then enter the following code in the index .js, where app.use that the middleware applies to all app.router('user') to middleware routed as the string 'user', ctx.body returns data to the small terminal return app.serve() :

  1. const cloud = require('wx-server-sdk')
  2. cloud.init({
  3. env: cloud.DYNAMIC_CURRENT_ENV,
  4. })
  5. const TcbRouter = require('tcb-router');
  6. exports.main = async (event, context) => {
  7. const app = new TcbRouter({event})
  8. const {OPENID} = cloud.getWXContext()
  9. app.use(async (ctx, next) => {//适用于所有的路由
  10. ctx.data = {} //声明data为一个对象
  11. await next();
  12. })
  13. app.router('user',async (ctx, next)=>{//路由为user
  14. ctx.data.openId = OPENID
  15. ctx.data.name = '李东bbsky'
  16. ctx.data.interest = ["爬山","旅游","读书"]
  17. ctx.body ={ //返回到小程序端的数据
  18. "openid":ctx.data.openId,
  19. "姓名":ctx.data.name,
  20. "兴趣":ctx.data.interest
  21. }
  22. })
  23. return app.serve()
  24. }

On the smaller side, we can call the created router cloud function with an event handler or lifecycle function, and we can get the object in ctx.body returned by the cloud function router in the res object:

  1. wx.cloud.callFunction({
  2. name: 'router',
  3. data: {
  4. $url: "user", //路由为字符串user,注意属性为 $url
  5. }
  6. }).then(res => {
  7. console.log(res)
  8. })

Second, tcb-router management database addition and deletion

Using tcb-router, we can also manage the collection of databases, we can integrate the add, remove, update, get, etc. of a collection (or multiple collections) into a cloud function, we can look at the following specific cases, we enter the following code in the router cloud function:

  1. const cloud = require('wx-server-sdk')
  2. cloud.init({
  3. env: cloud.DYNAMIC_CURRENT_ENV,
  4. })
  5. const TcbRouter = require('tcb-router');
  6. const db = cloud.database()
  7. const _ = db.command
  8. const $ = db.command.aggregate
  9. exports.main = async (event, context) => {
  10. const collection= "" //数据库的名称
  11. const app = new TcbRouter({event})
  12. const {adddata,deleteid,updatedata,querydata,updateid,updatequery} = event
  13. app.use(async (ctx, next) => {
  14. ctx.data = {}
  15. await next();
  16. });
  17. app.router('add',async (ctx, next)=>{
  18. const addresult = await db.collection(collection).add({
  19. data:adddata
  20. })
  21. ctx.data.addresult = addresult
  22. ctx.body = {"添加记录的返回结果":ctx.data.addresult}
  23. })
  24. app.router('delete',async(ctx,next)=>{
  25. const deleteresult = await db.collection(collection).where({
  26. id:deleteid
  27. }).remove()
  28. ctx.data.deleteresult = deleteresult
  29. ctx.body = {"删除记录的返回结果":ctx.data.deleteresult}
  30. })
  31. app.router('update',async(ctx,next)=>{
  32. const getdata = await db.collection(collection).where({
  33. id:updateid
  34. }).update({
  35. data:updatedata
  36. })
  37. ctx.data.getresult = getdata
  38. ctx.body = {"查询记录的返回结果":ctx.data.getresult}
  39. })
  40. app.router('get',async(ctx,next)=>{
  41. const getdata = await db.collection(collection).where(querydata).get()
  42. ctx.data.getresult = getdata
  43. ctx.body = {"查询记录的返回结果":ctx.data.getresult}
  44. })
  45. return app.serve();
  46. }

Then use wx.cloud.callFunction to pass in the appropriate cloud function and the corresponding $url and the corresponding data value in the corresponding event handler on the small terminal:

  1. //新增一条记录
  2. wx.cloud.callFunction({
  3. name: 'router',//router云函数
  4. data: {
  5. $url: "add",
  6. adddata:{
  7. id:"202006031020",
  8. title:"云数据库的最佳实践",
  9. content:"<p>文章的富文本内容</p>",
  10. createTime:Date.now()
  11. }
  12. }
  13. }).then(res => {
  14. console.log(res)
  15. })
  16. //删除一条记录
  17. wx.cloud.callFunction({
  18. name: 'router',
  19. data: {
  20. $url:"delete",
  21. deleteid:"202006031020"
  22. }
  23. }).then(res => {
  24. console.log(res)
  25. })
  26. //查询记录
  27. wx.cloud.callFunction({
  28. name: 'router',
  29. data: {
  30. $url:"get",
  31. querydata:{
  32. id:"202006031020",
  33. }
  34. }
  35. }).then(res => {
  36. console.log(res)
  37. })

For more advanced usage of tcb-router, you can view the technical documentation: tcb-router Github address. Some instructions when using tcb-router:

  • In general, we do not recommend that you use a cloud function to call other cloud functions, which results in a lot more time to execute the cloud function, but also consume the resources of the cloud function, we can use tcb-router to handle the need for cross-cloud function calls;

  • It is worth noting that tcb-router places the hosting of all cloud functions in one cloud function, and it is recommended not to put tcb-routers in one for cloud functions with higher requirements for synths. The maximum number of transactions per cloud function is 1000, which could have processed 100,000 levels of requests per second, but if a large number of different cloud functions are integrated into one, especially some of the longer-consuming cloud functions will seriously drag down performance, and these cloud functions will share these 1000 complex, so pay attention to the situation to choose;

  • Cloud functions will have a cold start time (e.g. no one calls this cloud function for more than ten minutes, and it will be slower to call this cloud function for the first time), when we integrate tcb-router into a cloud function with multiple functions that are similar in functionality and not particularly high (less than a few thousand per second), which reduces the likelihood of cold start;