[Fixed] Calling a Node.js module function from within main routes file

Issue

In my main routes file, I need to call a piece of code several times, so I am trying to put this piece of code in a separate module called ‘getDayWorkout’, so I dont have to repeat it over and over. I am struggling to accomplish this. Right now, the getDayWorkout function is triggered but it doesn’t get to the nested function in it. Below is the code in my main route file, followed by the code on the external module exported as ‘getDayWorkout’. Any help is appreciated.

const express = require('express')
const router = express.Router()
const connection = require('../../helpers/connection')
const getDayWorkout = require('../middlewares/getDayWorkout') // <= external module
    
router.get("/fetchcustomworkoutplan/:id", (req, res) => {
        console.log('MENFIS39: ', req.params)
        const userId = parseInt(req.params.id);
        let queryString = "SELECT day_one, day_two, day_three, day_four, day_five, day_six, day_seven FROM user_workout_plans WHERE user_id = ? AND status = ?"
        connection.query(queryString, [userId, 'Active'], async (err, rows, fields) => {
            if (err) {
                // // console.log(err)
                res.status(500).json({error: 'error'})
                return
            }
            if (rows.length === 0) {
                res.json(rows)
                return
            }
            console.log('wokour opans: ', rows)
            const userWorkoutPlans = rows[0]
            const { day_one, day_two, day_three, day_four, day_five, day_six, day_seven } = userWorkoutPlans
            if (day_one !== null) {
                
                    workoutDayOne = await getDayWorkout(day_one)
                
            }
            res.json(res.workoutPlans)
        })
    })

getDayWorkout File:

const connection = require('../../helpers/connection')

function getDayWorkout(dayWorkoutId) {
    console.log('here', dayWorkoutId) // <= triggered
    return (req, res, next) => {
        console.log('here2') // <=  triggered
        let queryString = "SELECT * FROM workout_sequences WHERE workout_id = ?"
        connection.query(queryString, [dayWorkoutId], (err, rows, fields) => {
            if (err) {
                // // console.log(err)
                res.status(500).json({error: 'error'})
                return
            }
            console.log('hit')
            return rows
        })
    }
}

module.exports = getDayWorkout;

Solution

If you want to return values from getDayWorkout method, you need either callback or promise. Since JS is asynchronous you cannot just return the value of an asynchronous calls.

Here is an implementation of Promise on which you can use await or then

const connection = require('../../helpers/connection')

function getDayWorkout(dayWorkoutId) {
    return new Promise((resolve, reject) => {
       console.log('here', dayWorkoutId) // <= triggered
       console.log('here2') // <=  triggered
       let queryString = "SELECT * FROM workout_sequences WHERE workout_id = ?"
       connection.query(queryString, [dayWorkoutId], (err, rows, fields) => {
          if (err) {
              reject(err);         
              return;
          }
          resolve(rows);
       });
    });
}

module.exports = getDayWorkout;

Leave a Reply

(*) Required, Your email will not be published