From d24b5ad50b9588e6a7ab3812d83841c49b5e9cba Mon Sep 17 00:00:00 2001 From: Wallef Reis Borges Date: Thu, 28 Nov 2019 21:00:21 +0000 Subject: [PATCH] Fixed bug when submitting an empty answer Submitting an empty answer would render the page again with the error message. It did not, however, had access to all the necessary data to display. The catch statement now has all the required data to render the page without breaking anything --- core/routes/answerRoutes.js | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/core/routes/answerRoutes.js b/core/routes/answerRoutes.js index 1f86599..95b0d10 100644 --- a/core/routes/answerRoutes.js +++ b/core/routes/answerRoutes.js @@ -24,30 +24,44 @@ router.get('/question/:question_id/answers', async ctx => { answers: answers } if (ctx.session.authorised === true) { - data.auth = ctx.session.authorised - data.username = ctx.session.user.username - data.avatarName = ctx.session.user.avatar - data.id = ctx.session.user.id + await pushSessionItemsToObject(data, ctx) } await ctx.render('answer', data) }) router.post('/question/:question_id/answer-action', async ctx => { try{ - const answer = await new Answer(process.env.DB_NAME) - const question = await new Question(process.env.DB_NAME) + const { question, answer } = await createObjects() const request = {body: ctx.request.body, parameters: ctx.params, session: ctx.session} const date = await question.currentDate(new Date()) await answer.createAnswer(request, date) ctx.redirect(`/question/${request.parameters.question_id}/answers`) } catch(err) { - const data = {title: ctx.params.question_id, content: 'Answers to a question', msg: err.message} + let question = await new Question(process.env.DB_NAME) + question = await question.getOneQuestion(ctx.params.question_id) + const answer = await new Answer(process.env.DB_NAME) + const answers = await answer.getAnswersByQuestion(ctx.params.question_id) + const data = {title: question.title, content: 'Answers to a question', msg: err.message, + question: question, answers: answers} if (ctx.session.authorised === true) { - data.auth = ctx.session.authorised - data.username = ctx.session.user.username + await pushSessionItemsToObject(data, ctx) } await ctx.render('answer', data) } }) module.exports = router + +async function createObjects() { + const answer = await new Answer(process.env.DB_NAME) + const question = await new Question(process.env.DB_NAME) + return { question, answer } +} + +async function pushSessionItemsToObject(object, context) { + object.auth = context.session.authorised + object.username = context.session.user.username + object.avatarName = context.session.user.avatar + object.id = context.session.user.id +} +