app.use inside a promise (bookshelf.js & express-basic-auth)

廉价感情. 提交于 2019-12-08 19:16:29

Okay so here is how I solved it.

async function runServerAuth (){
    let employee = await Api.fetchAll({columns: ['username','password']});
    employee = employee.toJSON();

    app.use(basicAuth({
            users: employee
    }));
    routes(app);
    app.listen(port);
    console.log('API server started on port: ' + port);
}

runServerAuth();

I simply put everything that is needed before I start the server together inside my async function (below the Promise which takes time to finish).

Thanks @TommyBs and @ChrisG for giving me the idea.

Though I believe this code could still be improved, but for now, this works.

You can use following structure -

Routes -

router.post("/home/all", [Lib.verifyToken.loginInRequired] , Controller.userChatController.homeAll);

And the Lib.verifyToken has following Method -

exports.loginInRequired = async function(request, response, next)
     {
    try{
    var data = request.body;
    data.userType = "User";

    if (!data.accessToken)
        return response.status(401).send({ success: -3, statusCode: 401, msg: response.trans("Your token has expired. Please login first")});

    var userDevice = await Service.userDeviceService.userMiddlewareGet(data);
    if(!userDevice)
        return response.status(401).send({ success: -3, statusCode: 401, msg: response.trans("Your token has expired. Please login first")});

    request.body.userDevice = userDevice;
    request.body.createdAt = moment.utc().format("YYYY-MM-DD HH:mm:ss");
    response.setLocale(userDevice.User.language);

    next();

   }
  catch(e)
   {
     return response.status(500).json({ success: 0, statusCode: 500, msg: e.message});
   }


};

This way you can add as many as middleware you need or even none.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!