egg(91)--egg之配置前臺公共中間件獲取數據(系統設置、公共導航、公共nav)

controller

app/controller/default/index.js

去掉請求頂部導航,中間導航,商品分類的請求數據庫

'use strict';

const Controller = require('egg').Controller;

class IndexController extends Controller {
  async index() {


   console.time('indextime');
   
   //輪播圖
   var focus=await this.ctx.service.cache.get('index_focus');
   if(!focus){
    focus=await this.ctx.model.Focus.find({"type":1});
    await this.ctx.service.cache.set('index_focus',focus,60*60);

   }
 
    //手機

    var shoujiResult=await this.ctx.service.cache.get('index_shoujiResult'); 

    if(!shoujiResult){
      shoujiResult=await this.service.goods.get_category_recommend_goods('5bbf058f9079450a903cb77b','best',8);
      await this.ctx.service.cache.set('index_shoujiResult',shoujiResult,60*60);

    }
    
    //電視
    var dianshiResult=await this.service.goods.get_category_recommend_goods('5bbf05ac9079450a903cb77c','best',10);

    

   console.timeEnd('indextime');


    await this.ctx.render('default/index',{     
      focus:focus,    
      shoujiResult:shoujiResult
    });
    
  }
}

module.exports = IndexController;

中間件middleware

app/middleware/init.js
module.exports = (options,app) => {
    return async function init(ctx, next) {
      

        // console.log(app);

        //獲取頂部導航的數據   
        var topNav=await ctx.service.cache.get('index_topNav');
        if(!topNav){
            topNav=await ctx.model.Nav.find({"position":1});
            await ctx.service.cache.set('index_topNav',topNav,60*60);
        }

        
        //商品分類
        var goodsCate=await ctx.service.cache.get('index_goodsCate');
        if(!goodsCate){
            goodsCate=await ctx.model.GoodsCate.aggregate([
                    
                {
                    $lookup:{
                    from:'goods_cate',
                    localField:'_id',
                    foreignField:'pid',
                    as:'items'      
                    }      
                },
                {
                    $match:{
                    "pid":'0'
                    }
                }

            ])
            await ctx.service.cache.set('index_goodsCate',goodsCate,60*60);

        }

        
            //中間導航以及關聯商品

        var middleNav=await ctx.service.cache.get('index_middleNav'); 
        if(!middleNav){
            middleNav=await ctx.model.Nav.find({"position":2});
            middleNav=JSON.parse(JSON.stringify(middleNav));  //一、不可擴展對象
            for(var i=0;i<middleNav.length;i++){     
                if(middleNav[i].relation){
                    //數據庫查找relation對應的商品            
                    try{
                        var tempArr=middleNav[i].relation.replace(/,/g,',').split(',');
                        var tempRelationIds=[];
                        tempArr.forEach((value)=>{
                            tempRelationIds.push({
                            "_id":app.mongoose.Types.ObjectId(value)
                            })
                        })
                        var relationGoods=await ctx.model.Goods.find({
                            $or:tempRelationIds
                        },'title goods_img');

                        middleNav[i].subGoods=relationGoods;

                    }catch(err){   //二、若是用戶輸入了錯誤的ObjectID(商品id)

                        middleNav[i].subGoods=[];
                    }
                }else{

                    middleNav[i].subGoods=[];
                }
            }

            await ctx.service.cache.set('index_middleNav',middleNav,60*60);
        

         }


        //  console.log(middleNav);

        ctx.state.topNav=topNav; 
        ctx.state.goodsCate=goodsCate; 
        ctx.state.middleNav=middleNav; 
        //注意
        await next();

    };
};

router.js

app/router/default.js

給須要使用頂部導航,中間導航,商品分類,增長中間件過濾app

module.exports = app => {
    const { router, controller } = app;
    //配置路由中間件
    var initMiddleware=app.middleware.init({},app);
    router.get('/', initMiddleware,controller.default.index.index);    
    router.get('/plist',initMiddleware, controller.default.product.list);
    router.get('/pinfo',initMiddleware, controller.default.product.info);
    router.get('/pinfo',initMiddleware, controller.default.product.info);
    router.get('/cart', initMiddleware,controller.default.flow.cart);
    //用戶中心
    router.get('/login', controller.default.user.login);
    router.get('/register', controller.default.user.register);
    router.get('/user', controller.default.user.welcome);
    router.get('/user/order', controller.default.user.order);
}

效果

頂部導航,中間導航,商品分類的數據async

clipboard.png

相關文章
相關標籤/搜索