Как передать мои параметры url асинхронным функциям в файлах javascript отдельно от маршрута с Node.js? - PullRequest
0 голосов
/ 15 апреля 2019

Я только учусь кодировать и создаю приложение для своего бизнеса.У меня проблема с передачей параметров URL-адреса на моем шоу-маршруте.

Я использую Node.js и MySQL.Маршрут отображает 7 различных отчетов, и я разбил каждый отчет на отдельные js-файлы, экспортировал функции и вызываю функции на show route для отображения страницы.Проблема в том, что мои запросы MySQL к каждой функции не являются динамическими, потому что я не могу получить доступ к параметрам url в каждом из этих отдельных файлов js.

Я пытался создать функцию на странице route.js, но запрос не определен, так как каждый запрос объявляется в маршруте.Я также пытался использовать $ {req.params.id} для отдельных файлов js, но req все еще не определено.

Вот мой маршрут показа:

router.get("/clients/:id/reports/monthlyreport/:marketplace/:month", function (req, res){
monthToMonth(function(arr){
    topSkuUnitsMonth(function(arr1){
        topSkuCogsMonth(function(arr2){
            productMix(function(arr3){
                ltmCogs(function(arr4){
                    topSkuCogsLTM(function(arr5){
                        topSkuUnitsLTM(function(arr6){
                            quarterComparison(function(arr7){
                                res.render("reports/show", {current: arr, math: math, units: arr1, cogs: arr2, mix: arr3, totals: arr4, yearCOGS: arr5, yearUnits: arr6, quarter: arr7});
                            })  
                        })
                    })
                })  
            })
        })  
    })
})  

});

Вот функция monthToMonth:

module.exports = function monthToMonth(callback){
var q = `select 
    t1.client_id,
    DATE_FORMAT(t1.period, '%Y-%m') as period,
    ROUND(t1.shipped_COGS,0) as shipped_COGS_current_month, 
    t1.shipped_units as shipped_units_current_month,
    t1.product_title as product_title_current_month, 
    t1.asin as asin_current_month,
    ROUND(t2.shipped_COGS,0) as shipped_COGS_past_month, 
    t2.shipped_units as shipped_units_past_month, 
    t2.product_title as product_title_past_month, 
    t2.asin as asin_past_month
    from all_months_ca t1
    join all_months_ca t2 on t1.asin = t2.asin
    where t1.client_id = 1 && t2.client_id  = 1 && (t1.shipped_units > 0 || t2.shipped_units > 0) && (DATE_FORMAT(t1.period, '%Y-%m') = '2019-05' && DATE_FORMAT(t2.period, '%Y-%m') = '2019-04')
    group by t1.asin
    order by shipped_COGS_current_month DESC;`
db.query(q, function(err, foundData){
    if(err) throw err;
    callback (foundData)
})

}

У запроса MySQL в настоящее время есть точка и client_id, жестко запрограммированные в предложении WHERE, но мне нужны параметры URL, чтобы сделать запросы динамическими.Как я могу передать параметры этим JS.файлы

1 Ответ

0 голосов
/ 19 апреля 2019

Почему бы не передать объект req в каждую функцию.

module.exports = function monthToMonth(req, callback){
var q = `select 
   t1.req.params.id,
   DATE_FORMAT(t1.period, '%Y-%m') as req.params.month,
   ROUND(t1.shipped_COGS,0) as shipped_COGS_current_month, 
   t1.shipped_units as shipped_units_current_month,
   t1.product_title as product_title_current_month, 
   t1.asin as asin_current_month,
   ROUND(t2.shipped_COGS,0) as shipped_COGS_past_month, 
   t2.shipped_units as shipped_units_past_month, 
   t2.product_title as product_title_past_month, 
   t2.asin as asin_past_month
   from all_months_ca t1
   join all_months_ca t2 on t1.asin = t2.asin
   where t1.client_id = 1 && t2.client_id  = 1 && (t1.shipped_units > 0 || t2.shipped_units > 0) && (DATE_FORMAT(t1.period, '%Y-%m') = '2019-05' &&    DATE_FORMAT(t2.period, '%Y-%m') = '2019-04')
   group by t1.asin
   order by shipped_COGS_current_month DESC;`
   db.query(q, function(err, foundData){
      if(err) throw err;
      callback (foundData)
   })

и вызвать эту функцию как -

 router.get("/clients/:id/reports/monthlyreport/:marketplace/:month", function (req, res){
  monthToMonth(req, function(arr){
  // call remaining function in same way.
  topSkuUnitsMonth(req, function(arr1){
})  })
...