Commit 0a10ca0f by Shaganaz

Corrected errors in admin and user models

parent d3c42eff
......@@ -4,8 +4,8 @@ meta {
seq: 4
}
post {
url: http://localhost:3000/api/admin/assign-quiz
get {
url: http://localhost:3000/api/admin/quizzes
body: json
auth: bearer
}
......@@ -15,12 +15,5 @@ headers {
}
auth:bearer {
token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjIsImVtYWlsIjoiYWRtaW5AZ21haWwuY29tIiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNzQ4OTUzNDIxLCJleHAiOjE3NDg5NTcwMjF9.jc1Y0rh69qKpFe-fkYHnLYnukO7nAkCiTRjFUxYsiFE
}
body:json {
{
"user_id": 1,
"quiz_id": 3
}
token:
}
......@@ -16,9 +16,9 @@ headers {
body:json {
{
"email": "admin@gmail.com",
"password": "admin@123",
"role": "admin"
"email": "siva@gmail.com",
"password": "siva",
"role": ""
}
......
......@@ -5,7 +5,7 @@ meta {
}
get {
url: /api/user/take-quiz/3/1
url: http://localhost:3000/api/user/take-quiz/2/1
body: json
auth: bearer
}
......@@ -15,5 +15,5 @@ headers {
}
auth:bearer {
token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsImVtYWlsIjoic2hhZ2FuYXpAZ21haWwuY29tIiwicm9sZSI6InVzZXIiLCJpYXQiOjE3NDg5NTQzMDAsImV4cCI6MTc0ODk1NzkwMH0.9GOhjHWK7ugeiWGTiElWFpdGYS0GdnB9mTkZSkNc7Ok
token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjIsImVtYWlsIjoic2hhZ2FuYXpAZ21haWwuY29tIiwicm9sZSI6IiIsImlhdCI6MTc0OTAzMjcwMiwiZXhwIjoxNzQ5MDM2MzAyfQ.Ma9h9-CZbQRbZYtIk6Vxv01VCsU0ReevBWfKymzVhII
}
......@@ -2,7 +2,7 @@
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('Users', {
await queryInterface.createTable('users', {
id: {
allowNull: false,
autoIncrement: true,
......@@ -29,6 +29,6 @@ module.exports = {
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('Users');
await queryInterface.dropTable('users');
}
};
\ No newline at end of file
......@@ -4,11 +4,6 @@ const {
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class option extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
option.belongsTo(models.question,{
foreignKey:'question_id',
......
......@@ -5,16 +5,14 @@ const {
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class question extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
question.belongsTo(models.quiz,{
foreignKey:'quiz_id',
onDelete:'cascade'
})
question.hasMany(models.option, { foreignKey: 'question_id' , as:'options'});
question.hasOne(models.option, { foreignKey: 'question_id' , as:'correctOption',scope:{is_correct:true}});
}
}
question.init({
......
......@@ -5,6 +5,7 @@ const {
module.exports = (sequelize, DataTypes) => {
class quiz extends Model {
static associate(models) {
quiz.hasMany(models.question, { foreignKey: 'quiz_id', as:'questions'});
}
}
quiz.init({
......
......@@ -4,11 +4,6 @@ const {
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class result extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
result.belongsTo(models.user,{
foreignKey:'user_id',
......
......@@ -4,13 +4,7 @@ const {
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class user extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
}
user.init({
......@@ -20,7 +14,7 @@ module.exports = (sequelize, DataTypes) => {
}, {
sequelize,
modelName: 'user',
tableName:'Users'
tableName:'users'
});
return user;
};
\ No newline at end of file
......@@ -4,11 +4,6 @@ const {
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class user_answers extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
user_answers.belongsTo(models.user,{
foreignKey:'user_id',
......
......@@ -4,11 +4,6 @@ const {
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class user_quizzes extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
user_quizzes.belongsTo(models.user,{
foreignKey:'user_id',
......
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up (queryInterface, Sequelize) {
await queryInterface.bulkInsert('quizzes', [
{
id:1,
title: 'Math Quiz',
description: 'Basic math questions',
createdAt: new Date(),
updatedAt: new Date()
},
{
id:2,
title: 'Science Quiz',
description: 'General science',
createdAt: new Date(),
updatedAt: new Date()
}
]);
const mathsQuizId=1
await queryInterface.bulkInsert('questions', [
{
quiz_id: mathsQuizId,
question_text: 'What is 2 + 2?',
createdAt: new Date(),
updatedAt: new Date()
},
{
quiz_id: mathsQuizId,
question_text: 'What is 10 - 4?',
createdAt: new Date(),
updatedAt: new Date()
}
]);
await queryInterface.bulkInsert('options', [
{
question_id: 1,
option_text: '3',
is_correct: false,
createdAt: new Date(),
updatedAt: new Date()
},
{
question_id: 1,
option_text: '4',
is_correct: true,
createdAt: new Date(),
updatedAt: new Date()
},
{
question_id: 1,
option_text: '5',
is_correct: false,
createdAt: new Date(),
updatedAt: new Date()
},
{
question_id: 2,
option_text: '5',
is_correct: false,
createdAt: new Date(),
updatedAt: new Date()
},
{
question_id: 2,
option_text: '6',
is_correct: true,
createdAt: new Date(),
updatedAt: new Date()
},
{
question_id: 2,
option_text: '7',
is_correct: false,
createdAt: new Date(),
updatedAt: new Date()
}
]);
},
async down (queryInterface, Sequelize) {
await queryInterface.bulkDelete('quizzes', null, {});
await queryInterface.bulkDelete('questions', null, {});
await queryInterface.bulkDelete('options', null, {});
}
};
......@@ -11,6 +11,20 @@ exports.createQuiz=async(req,res)=>{
}
};
exports.getAllQuizzes = async (req, res) => {
try {
const quizzes = await db.quiz.findAll({
attributes: ['id', 'title', 'description'],
order: [['id', 'ASC']]
});
return res.json(quizzes);
} catch (err) {
console.log(err);
return res.json({ message: 'Error fetching quizzes', error: err.message });
}
};
exports.createQuestion = async (req, res) => {
const { quiz_id, question_text,options,correct_answer } = req.body;
try {
......@@ -33,6 +47,7 @@ exports.assignQuiz = async (req, res) => {
await db.user_quizzes.create({user_id, quiz_id, status:'pending'});
return res.json({ message: 'Quiz assigned to user successfully' });
} catch (err) {
console.log();
return res.json({ message: 'Unable to assign quiz', error: err.message });
}
};
......@@ -41,7 +56,7 @@ exports.getUserResult = async (req, res) => {
const { user_id, quiz_id } = req.params;
try {
const answers = await db.user_answer.findAll({
const answers = await db.user_answers.findAll({
where: { user_id, quiz_id },
include: [
{
......
......@@ -2,7 +2,8 @@ const jwt = require('jsonwebtoken');
const db = require('../../models');
exports.register = async (req, res) => {
const { email, password, role = 'user' } = req.body;
const { email, password } = req.body;
const role = req.body.role && req.body.role.trim() !== '' ? req.body.role : 'user';
try {
const existing = await db.user.findOne({ where: { email } });
......@@ -10,9 +11,9 @@ exports.register = async (req, res) => {
return res.json({ message: 'User already registered' });
}
await db.user.create({ email, password, role });
res.json({ message: 'User registered successfully' });
return res.json({ message: 'User registered successfully' });
} catch (err) {
res.json({ message: 'Registration failed', error: err.message });
return res.json({ message: 'Registration failed', error: err.message });
}
};
......@@ -32,12 +33,12 @@ exports.login = async (req, res) => {
{ expiresIn: process.env.JWT_EXPIRES_IN }
);
res.json({
return res.json({
message: 'Login successful',
token,
role: user.role
});
} catch (err) {
res.status(500).json({ message: 'Login failed', error: err.message });
return res.status(500).json({ message: 'Login failed', error: err.message });
}
};
const db = require('../../models');
exports.takeQuiz=async(req,res)=>{
console.log(req.params);
const {quiz_id,user_id}=req.params;
try{
const assigned =await db.user_quizzes.findOne({where:{user_id,quiz_id,status:'pending'}});
......@@ -9,25 +10,30 @@ exports.takeQuiz=async(req,res)=>{
}
const quiz=await db.quiz.findByPk(quiz_id,{
attributes:['id','title','description'],
include:{
include:[{
model:db.question,
as:'questions',
attributes:['id','question_text'],
include:{
include:[{
model:db.option,
as:"options",
attributes:['id','option_text']
}
},
}]
}],
order:[
[db.question,'id','ASC'],
[db.question,db.option,'id','ASC']
['questions','id','ASC'],
['questions','options','id','ASC']
]
});
console.log('quizzz');
console.log(quiz);
if(!quiz){
return res.json({message:'Quiz not found'});
}
return res.json({quiz});
}
catch(err){
console.log(err);
return res.json({message:"Error fetching quiz",error:err.message});
}
};
......@@ -35,19 +41,26 @@ exports.takeQuiz=async(req,res)=>{
exports.submitQuiz = async (req, res) => {
const { user_id, quiz_id, answers } = req.body;
try {
const alreadySubmitted = await db.user_quizzes.findOne({
where: { user_id, quiz_id, status: 'completed' }
});
if (alreadySubmitted) {
return res.json({ message: 'Quiz already submitted' });
}
let score = 0;
const total = answers.length;
for (const ans of answers) {
const correct= await db.option.findOne({where:{id:ans.selected_option_id}});
const isCorrect = correct[0]?.is_correct === 1 ? 1 : 0;
const isCorrect = correct.is_correct ?? 0
if (isCorrect) score++;
await db.user_answer.create({user_id, quiz_id, question_id:ans.question_id, answer:ans.selected_option_id, is_correct:isCorrect});
await db.user_answers.create({user_id, quiz_id, question_id:ans.question_id, answer:ans.selected_option_id, is_correct:isCorrect});
}
await db.results.create({user_id, quiz_id, score, total});
await db.result.create({user_id, quiz_id, score, total});
await db.user_quizzes.update({status:'completed'},{where:{user_id,quiz_id}});
return res.json({ message: 'Quiz submitted', score, total });
} catch (err) {
return res.status(500).json({ message: 'Error submitting quiz', error: err.message });
return res.json({ message: 'Error submitting quiz', error: err.message });
}
};
......
......@@ -4,6 +4,7 @@ const authenticateAdmin=require('../middleware/authmiddleware');
const adminctrl=require('../controller/adminController.js');
router.post('/create-quiz',authenticateAdmin,adminctrl.createQuiz);
router.get('/quizzes', authenticateAdmin, adminctrl.getAllQuizzes);
router.post('/create-question',authenticateAdmin,adminctrl.createQuestion);
router.post('/assign-quiz', authenticateAdmin, adminctrl.assignQuiz);
router.get('/user-result/:user_id/:quiz_id', authenticateAdmin, adminctrl.getUserResult);
......
......@@ -4,10 +4,10 @@ const authenticateAdmin=require('../middleware/authmiddleware');
const authenticateUser = require('../middleware/usermiddleware');
router.get('/admin',authenticateAdmin,(req,res)=>{
res.json({message:'Welcome to Admin Dashboard'});
return res.json({message:'Welcome to Admin Dashboard'});
});
router.get('/user',authenticateUser,(req,res)=>{
res.json({message:'Welcome to User Dashboard'});
return res.json({message:'Welcome to User Dashboard'});
})
module.exports=router;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment