Node js Sequelize repository pattern (node:2944) UnhandledPromiseRejectionWarning: TypeError: is not a function

I recently got aware of repository pattern. I am quite new to this pattern and tried to shift my code in this patter. I am using Node js and Sequelize ORM with Sqlite database.

Following route is working

router.get('/listquestions',(req,res)=>{
    Question.findAll({  
     attributes: ['id','title'],
     include: [{
            model:Lecture,
            attributes: ['id','videoname','coursecode'],
        }]
    }).then((questions) => {
        if(questions){
            console.log(JSON.stringify(questions));
            res.render('pages/questionslist', {data:questions});
            //res.send(JSON.stringify(questions));          
        }else{
            res.send ("No question found");
        }
    }).catch((err) => res.send(err));
});


but when I tried to shift kind of similar function into repository pattern. I am quit confuse how to write the promise call. This is how my question-repository.js file looks in repository folder

const Question = require('../db').Question;
const QOptions = require('../db').QOptions;

var QuestionsRepository = {
    findById: async function(id) {
       return Question.findAll({
            attributes: ['id','title'],
            where: {
                id: id              
            },
            include: [{
                model:QOptions,
                attributes: ['id','option_text'],
            }]
        })
    }
}

I am trying to call this function like this

const QuestionsRepository = require('./repository/question-repository');
router.get('/qbyid',(req,res)=>{
QuestionsRepository.findById(req.query.qid).then((q)=>{
                if(q){
                    res.send(JSON.stringify(q));
                }
            })
});

But it does not work. It throws error which says


Executing (default): SELECT `id`, `iscorrect` FROM `options` AS `options` WHERE
`options`.`question_id` = '7' AND `options`.`iscorrect` = 1;
(node:2944) UnhandledPromiseRejectionWarning: TypeError: QuestionsRepository.fin
dById is not a function
    at C:UsersStrange Labnodejs-projectsexpresstestquestionroutes.js:30:24
(node:2944) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function without a catch
block, or by rejecting a promise which was not handled with .catch(). To termina
te the node process on unhandled promise rejection, use the CLI flag `--unhandle
d-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejectio
ns_mode). (rejection id: 1)
(node:2944) [DEP0018] DeprecationWarning: Unhandled promise rejections are depre
cated. In the future, promise rejections that are not handled will terminate the
 Node.js process with a non-zero exit code.


I also tried calling the function with Catch block like this

QuestionsRepository.findById(7).then((q)=>{
                if(q){
                    res.send(JSON.stringify(q));
                }
            }).catch((err) => {
                 res.redirect('/questionadd?'
                    +qs.stringify({error:err.message}));
            });

(Although I do not want to write this messy then() and catch() statements which just increasing the verbose) but even by including this catch block doesn’t effect on error.

What would be the best way (good practice) to write repository pattern in my current scenario? and How to properly handle promise rejection and errors as well?

Source: Ask Javascript Questions

2 thoughts on - Node js Sequelize repository pattern (node:2944) UnhandledPromiseRejectionWarning: TypeError: is not a function

  • Maybe you have worked it out, as this is rather old. You have nothing exported in “question-repository.js”. You can (1) add

    “`module.exports = QuestionRepository;“`

    to the end of the file or you can (2) skip defining the var (which could have been a const) and export the object literal.

LEAVE A COMMENT