1

I want to build a navbar dynamically according to users permissions.

So when the user is logged in, I'm going call 'exports.getMenu' to execute a query which will help me to build it.

But I'm having trouble to get the value(query.rows) outside of the scope of the function and then store it on 'res.locals' from Express.

What is the proper way to get the values and have access to it during the request?

server.js

var express = require('express');
var menus = require('./config/menu');
require('./config/passport');
var app = express();

app.use(function(req, res, next) 
{
    res.locals.user = req.user ? req.user.toJSON() : null;
    if(typeof res.locals.user !== 'undefined')
    {
        if(res.locals.user != null && res.locals.user.id != null)
        {
            menus.getMenu(req, res, next);                 
        }
    }
    next();
});

menu.js

var bookshelf = require('../config/bookshelf');

exports.getMenu  = function(req, res, next)
{
    var sql = "select * from menus"; // Suppose its the query i'm going to execute

   menus = bookshelf.knex.raw(sql).then(function(query)
   {
        return JSON.stringify(query.rows);
   });
};

I checked this question but I'm having a difficulty to apply the solution. For example one of the solutions described:

function delay() {
  // `delay` returns a promise
  return new Promise(function(resolve, reject) {
    // Only `delay` is able to resolve or reject the promise
    setTimeout(function() {
      resolve(42); // After 3 seconds, resolve the promise with value 42
    }, 3000);
  });
}

delay()
  .then(function(v) { // `delay` returns a promise
    console.log(v); // Log the value once it is resolved
  })
  .catch(function(v) {
    // Or do something else if it is rejected 
    // (it would not happen in this example, since `reject` is not called).
  });

In this case the 'delay function' was created by the user.

In my question I'm using a method from Bookshelf Js.

So if I want to use this solution I have to overwrite Bookshelf/Knex function?

My doubt also goes for the case of using 'callbacks'. If I use 'callbacks' I need to change how Bookshelf function works?

Ulisses
  • 11
  • 2

0 Answers0