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

假装没事ソ 提交于 2020-12-15 03:47:23

问题


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:\Users\Strange Lab\nodejs-projects\expresstest\questionroutes.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?

来源:https://stackoverflow.com/questions/65181926/node-js-sequelize-repository-pattern-node2944-unhandledpromiserejectionwarnin

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