<file_sep>module.exports = fn => (req, res, next) => {
    Promise.resolve(fn(req, res, next)).catch(err => {
        next(err === undefined ? 'Unknown error occurred' : err);
    });
};<file_sep>const express = require('express');
const router = express.Router();
const db = require('../models');
const asyncWrap = require('../middleware/asyncWrap');

router.post('/add-visit', asyncWrap(async (req, res) => {
    const currentCount = await db.config.findOne({ where: {
            id: 1,
        }
    });

    try {
        const incrementResult = await currentCount.increment('visit_count', { by: 1 })

        res.status(201).send({ success: true, result: incrementResult });
    } catch (e) {
        console.log(e);
        res.status(400).send(e);
    }
}));

router.get('/get-statistics', asyncWrap(async (req, res, next) => {
    const usersCount = await db.users.findAll();
    const visits = await db.config.findAll();
    const visitCount = visits[0]?.dataValues?.visit_count;
    const lessonsCount = await db.lessons.findAll();
    if (!usersCount || !visitCount || !lessonsCount) {
        return res.status(404).json({ success: false, message: 'Some of statistics are missing' });
    }
    else {
        res.status(200).send({ success: true, statistics: {
                users: usersCount.length,
                visits: visitCount,
                lessons: lessonsCount.length,
            }
        });
    }
}));

module.exports = router;<file_sep>const express = require('express');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const cors = require('cors')

const indexRouter = require('./routes/index');
const globalRouter = require('./routes/global');
const authRouter = require('./routes/auth')
const usersRouter = require('./routes/users');
const lessonRouter = require('./routes/lessons');
const chapterRouter = require('./routes/chapters');
const sectionRouter = require('./routes/sections');
const testRouter = require('./routes/test');
const commentsRouter = require('./routes/comments')

const app = express();

const Options = {
    origin: ["http://localhost:3000"],
    allowedHeaders: [
        "Content-Type",
        "Authorization",
        "Access-Allow-Origin-Control",
        "Access-Control-Request-Headers",
    ],
    credentials: true,
    enablePreflight: true,
}

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(cors(Options));

// app.use('/auth', require('./auth'));

// app.use(require('./middleware/auth'));

app.use('/', indexRouter);
app.use('/global', globalRouter);
app.use('/auth', authRouter);
app.use('/users', usersRouter);
app.use('/lessons', lessonRouter);
app.use('/chapters', chapterRouter);
app.use('/sections', sectionRouter);
app.use('/test', testRouter);
app.use('/comment', commentsRouter)

module.exports = app;
<file_sep>const express = require('express');
const router = express.Router();
const db = require('../models');
const asyncWrap = require('../middleware/asyncWrap');
const bcrypt = require('bcryptjs');

router.post('/sign-up', asyncWrap(async (req, res) => {
  const { first_name, last_name, email, password } = req.body;
  const hashedPass = bcrypt.hashSync(password, 13);
  if (!req.body.email || !req.body.password) {
    res.status(400).send({
      status: false,
      message: 'Fields are required!'
    });
  } else {
    await db.users.create({
      email,
      password: <PASSWORD>,
      first_name,
      last_name,
      type: 'user',
    }).then(() => {
      res.status(201).send({ success: true });
    }).catch((error) => {
      res.status(400).send(error);
    });
  }
}))

module.exports = router;
<file_sep>const express = require('express');
const router = express.Router();
const db = require('../models');
const asyncWrap = require('../middleware/asyncWrap');

router.get('/get-sections', asyncWrap(async (req, res, next) => {
    const { chapter_id } = req.query;
    const sections = await db.sections.findAll({
        where: {
            chapterId: chapter_id,
        }
    });
    if (!sections)
        return res.status(404).json({ success: false, message: 'No Section found' });
    else {
        const sectionsResponse = sections?.map((section) => {
            return {
                id: section.id,
                title: section.title,
            };
        })
        res.status(200).send({ success: true, sections: sectionsResponse });
    }
}));

router.post('/create-section', asyncWrap(async (req, res) => {
    const { section, id } = req.body;
    if (!section) {
        res.status(400).send({
            status: false,
            message: 'Field is required!'
        });
    } else {
        let result;
        try {
            result = await db.sections.create({
                title: section,
                chapterId: id,
            })
            res.status(201).send({success: true});
        } catch (e) {
            console.log(e);
            res.status(400).send(e);
        }
    }
}));

module.exports = router;<file_sep>const express = require('express');
const router = express.Router();
const db = require('../models');
const asyncWrap = require('../middleware/asyncWrap');

router.get('/get-chapters', asyncWrap(async (req, res, next) => {
    const chapters = await db.chapters.findAll();
    if (!chapters)
        return res.status(404).json({ success: false, message: 'No lesson found' });
    else {
        const chaptersResponse = chapters?.map((chapter) => {
            return {
                id: chapter.id,
                title: chapter.title,
            };
        })
        res.status(200).send({success: true, chapters: chaptersResponse });
    }
}));

router.post('/create-chapter', asyncWrap(async (req, res) => {
    const { chapter } = req.body;
    if (!chapter) {
        res.status(400).send({
            status: false,
            message: 'Field is required!'
        });
    } else {
        let result;
        try {
            result = await db.chapters.create({
                title: chapter,
            })

            res.status(201).send({ success: true });
        } catch (e) {
            console.log(e);
            res.status(400).send(e);
        }
    }
}));

module.exports = router;<file_sep>const express = require('express');
const router = express.Router();
const db = require('../models');
const asyncWrap = require('../middleware/asyncWrap');


router.get('/get-tests', asyncWrap(async (req, res) => {
    const { sectionId } = req.query;
    const tests = await db.tests.findAll({
        where: {
            sectionId: +sectionId,
        },
        attributes: [
            'id',
        ],
        include: [
            {
                model: db.questions,
                attributes: [
                    'id',
                    'testId',
                    'question',
                ],
                include: [
                    {
                        model: db.answers,
                        attributes: [
                            'id',
                            'questionId',
                            'option',
                        ]
                    }
                ]
            }
        ]
    });
    if (!tests)
        return res.status(404).json({ success: false, message: 'No Test found' });
    else {
        res.status(200).send({ success: true, tests });
    }
}))

router.post('/create-test', asyncWrap(async (req, res) => {
    const { data, sectionId, questionsCount } = req.body;
    if (!data || !sectionId) {
        res.status(400).send({
            status: false,
            message: 'Fields are required!'
        });
    } else {
        let testResult
        let result;
        try {
            for(let i = 0; i < questionsCount; i++) {
                testResult = await db.tests.create({
                    sectionId,
                })
                result = await db.questions.create({
                    testId: testResult.dataValues.id,
                    question: data[`question_${i}`],
                })
                await [1,2,3,4].forEach((_, index) => (
                    db.answers.create({
                        questionId: result.dataValues.id,
                        option: data[`answer_${i}_${index}`],
                        isCorrect: data[`correct_${i}_${index}`],
                    })
                ))
            }
            res.status(201).send({ success: true });
        } catch (e) {
            console.log(e);
            res.status(400).send(e);
        }
    }
}));

router.post('/submit-test', asyncWrap(async (req, res) => {
    const { answers, sectionId } = req.body;
    const tests = await db.tests.findAll({
        where: {
            sectionId: +sectionId,
        },
        attributes: [
            'id',
        ],
        include: [
            {
                model: db.questions,
                attributes: [
                    'id',
                    'testId',
                    'question',
                ],
                include: [
                    {
                        model: db.answers,
                        attributes: [
                            'id',
                            'questionId',
                            'option',
                            'isCorrect',
                        ]
                    }
                ]
            }
        ]
    });
    const correctAnswers = tests.map(val => val.questions[0].answers.map(answer => answer.dataValues));
    const correctOptions = correctAnswers.map (item => item.find(option => option.isCorrect));
    const rightAnswerIds = Object.values(answers);
    const matchingOptions = correctOptions.map(option => rightAnswerIds.includes(option.id.toString()));
    let correctAnswersCount = matchingOptions.filter(value => !!value).length;
    res.status(200).send({ success: true, data: { correctOptions, correctAnswersCount }});
}));


module.exports = router;<file_sep>const jwt = require('jsonwebtoken');
const User = require('../models/users');
const asyncWrap = require('./asyncWrap');

module.exports = asyncWrap(async (req, res, next) => {
    const token = req.headers['x-access-token'];
    if (!token)
        return res
            .status(401)
            .send({ success: false, message: 'No token provided.' });

    jwt.verify(token, '<PASSWORD>', async (err, decoded) => {
        if (err)
            return res
                .status(500)
                .send({ success: false, message: 'Failed to authenticate token.' });

        const user = await User.findById(decoded.id, { password: 0 });
        if (!user) {
            return res.status(404).send('No user found.');
        }

        req.user = user;

        next();
    });
});