Skip to content

Commit

Permalink
create: POST /questions endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
NBNARADHYA committed Dec 15, 2020
1 parent 31d58c2 commit 79a0247
Show file tree
Hide file tree
Showing 7 changed files with 183 additions and 3 deletions.
122 changes: 122 additions & 0 deletions server/models/questions/createQuestion.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
const { pool } = require('../database')

/**
*
* @param {*} param0
* @param {String} param0.username
* @param {String} param0.name
* @param {String} param0.problem_statement
* @param {String} param0.type
* @param {String} param0.input_format
* @param {String} param0.output_format
* @param {String} param0.constraints
* @param {Array} param0.options
* @param {Number} param0.correct
* @param {String} param0.difficulty
* @param {Array} param0.tags
* @return {Promise}
*/

function createQuestion({
username,
name,
problem_statement: problemStatement,
type,
input_format: inputFormat,
output_format: outputFormat,
constraints,
options,
correct,
difficulty,
tags,
}) {
return new Promise((resolve, reject) => {
pool.getConnection((err, connection) => {
if (err) {
return reject(err)
}
connection.beginTransaction((err) => {
if (err) {
connection.release()
return reject(err)
}
connection.query(
`INSERT INTO questions(creator,type,name,problem_statement,input_format,
output_format,constraints,options,correct,difficulty)
VALUES(?,?,?,?,?,?,?,?,?,?)`,
[
username,
type,
name,
problemStatement,
inputFormat,
outputFormat,
constraints,
JSON.stringify(options),
correct,
difficulty,
],
(error, results) => {
if (error || !results) {
connection.release()
return reject(error)
}

const questionId = results.insertId

if (!tags || !tags.length) {
return connection.commit((error) => {
if (error) {
return connection.rollback(() => {
connection.release()
return reject(error)
})
}
connection.release()
return resolve({
message: 'Question created successfully',
questionId,
})
})
}

let query = `INSERT INTO questions_tags(question_id, tag_id) VALUES`
const queryArr = []

tags.forEach((tag, idx) => {
query += `(?,?)`
if (idx !== tags.length - 1) {
query += `,`
}
queryArr.push(questionId, tag)
})

connection.query(query, queryArr, (error) => {
if (error) {
return connection.rollback(() => {
connection.release()
return reject(error)
})
}
return connection.commit((error) => {
if (error) {
return connection.rollback(() => {
connection.release()
return reject(error)
})
}
connection.release()
return resolve({
message: 'Question created successfully',
questionId,
})
})
})
}
)
})
})
})
}

module.exports = createQuestion
3 changes: 3 additions & 0 deletions server/models/questions/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const createQuestion = require('./createQuestion')

module.exports = { createQuestion }
4 changes: 3 additions & 1 deletion server/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const groupsRouter = require('./groups')
const notificationsRouter = require('./notifications')
const searchRouter = require('./search')
const contestsRouter = require('./contests')
// const questionsRouter = require('./questions')
const questionsRouter = require('./questions')
// const submissionsRouter = require('./submissions')
const tagsRouter = require('./tags')

Expand Down Expand Up @@ -69,6 +69,8 @@ router.use('/contests', contestsRouter.removeGroupRouter)
// router.use('/contests', contestsRouter.getLeaderboardRouter)
// router.use('/contests', contestsRouter.getQuestionLeaderboardRouter)

router.use('/questions', questionsRouter.createQuestion)

router.use('/tag', tagsRouter.createTagRouter)
router.use('/tag', tagsRouter.getTagRouter)

Expand Down
45 changes: 45 additions & 0 deletions server/routes/questions/createQuestion.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const express = require('express')
const { verifyUserAccessToken, verifyAdmin } = require('../middlewares')
const router = express.Router()
const ajv = require('../../schema')
const { createQuestionSchema } = require('../../schema/questions')
const { createQuestion } = require('../../models/questions')

/**
*
* @param {Array} errArray
* @return {String}
*/
function sumErrors(errArray) {
const cb = (a, b) => a + b.message + ', '
return errArray.reduce(cb, '')
}

router.post('/', verifyUserAccessToken, verifyAdmin, (req, res) => {
const validate = ajv.compile(createQuestionSchema)
const isValid = validate(req.body)
if (!isValid) {
return res.status(400).json({
success: false,
error: sumErrors(validate.errors),
results: null,
})
}
createQuestion({ ...req.body, username: req.username })
.then((results) => {
return res.status(200).json({
success: true,
results,
error: null,
})
})
.catch((error) => {
return res.status(400).json({
success: false,
results: null,
error,
})
})
})

module.exports = router
3 changes: 3 additions & 0 deletions server/routes/questions/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const createQuestion = require('./createQuestion')

module.exports = { createQuestion }
7 changes: 6 additions & 1 deletion server/schema/questions/createQuestion.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ module.exports = {
},
options: {
type: 'array',
pattern: 'optionsPattern',
pattern: 'arrPattern',
},
correct: {
type: 'number',
Expand All @@ -31,6 +31,10 @@ module.exports = {
type: 'string',
enum: ['easy', 'medium', 'hard'],
},
tags: {
type: 'array',
pattern: 'arrPattern',
},
},
errorMessage: {
required: {
Expand All @@ -47,6 +51,7 @@ module.exports = {
options: 'Invalid question options',
correct: 'Invalid question correct field',
difficulty: 'Invalid question difficulty',
tags: 'Invalid question tags',
},
_: 'Invalid data',
},
Expand Down
2 changes: 1 addition & 1 deletion server/schema/questions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const ajv = require('../index')
const createQuestionSchema = require('./createQuestion')
const updateQuestionSchema = require('./updateQuestion')

ajv.addFormat('optionsPattern', (data) =>
ajv.addFormat('arrPattern', (data) =>
Array.isArray(JSON.parse(JSON.stringify(data)))
)

Expand Down

0 comments on commit 79a0247

Please sign in to comment.