Skip to content

Commit

Permalink
Merge pull request #356 from bounswe/backend/development
Browse files Browse the repository at this point in the history
Backend/development
  • Loading branch information
EmreBatuhan authored Nov 14, 2023
2 parents 58a7f0b + 1e883bc commit 10e38aa
Show file tree
Hide file tree
Showing 10 changed files with 872 additions and 25 deletions.
2 changes: 1 addition & 1 deletion prediction-polls/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"main": "app.js",
"scripts": {
"test": "jest",
"devStart": "nodemon src/app.js"
"start": "nodemon src/app.js"
},
"keywords": [],
"author": "",
Expand Down
4 changes: 3 additions & 1 deletion prediction-polls/backend/src/app.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const express = require('express');
const authRouter = require('./routes/AuthorizationRouter.js');
const pollRouter = require('./routes/PollRouter.js');

const cors = require("cors");

Expand All @@ -16,7 +17,8 @@ app.use(cors());
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

app.use('/', authRouter);
app.use('/polls',pollRouter);
app.use('/auth', authRouter);

const swaggerSpec = swaggerJsDoc(swaggerOptions);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
Expand Down
169 changes: 169 additions & 0 deletions prediction-polls/backend/src/repositories/PollDB.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
const mysql = require('mysql2')

require('dotenv').config();

const pool = mysql.createPool({
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE
}).promise()


async function getDiscretePolls(){
const sql = 'SELECT * FROM discrete_polls';

try {
const [rows, fields] = await pool.query(sql);
return rows
} catch (error) {
console.error('getDiscretePolls(): Database Error');
throw error;
}
}

async function getContinuousPolls(){
const sql = 'SELECT * FROM continuous_polls';

try {
const [rows, fields] = await pool.query(sql);
return rows
} catch (error) {
console.error('getDiscretePolls(): Database Error');
throw error;
}
}

async function getDiscretePollWithId(pollId){
const sql = 'SELECT * FROM discrete_polls WHERE id = ?';

try {
const [rows, fields] = await pool.query(sql, [pollId]);
return rows;
} catch (error) {
console.error('getDiscretePollWithId(): Database Error');
throw error;
}

}

async function getContinuousPollWithId(pollId){
const sql = 'SELECT * FROM continuous_polls WHERE id = ?';

try {
const [rows, fields] = await pool.query(sql, [pollId]);
return rows;
} catch (error) {
console.error('getContinuousPollWithId(): Database Error');
throw error;
}
}

async function addDiscretePoll(question, choices){
const sql_poll = 'INSERT INTO discrete_polls (question) VALUES (?)';
const sql_choice = 'INSERT INTO discrete_poll_choices (choice_text, poll_id) VALUES (?, ?)';

try {
const [resultSetHeader] = await pool.query(sql_poll, [question]);
poll_id = resultSetHeader.insertId;
if (!poll_id) {
return false;
}
await Promise.all(choices.map(choice => {
return pool.query(sql_choice, [choice, poll_id]);
}))
return true;
} catch (error) {
console.error('addDiscretePoll(): Database Error');
throw error;
}
}

async function addContinuousPoll(question, min, max){
const sql_poll = 'INSERT INTO continuous_polls (question, min_value, max_value) VALUES (?, ?, ?)';

try {
const [resultSetHeader] = await pool.query(sql_poll, [question, min, max]);
poll_id = resultSetHeader.insertId;
if (!poll_id) {
return false;
}
return true;
} catch (error) {
console.error('addContinuousPoll(): Database Error');
throw error;
}
}

async function getDiscretePollChoices(pollid) {
const sql = "SELECT * FROM discrete_poll_choices WHERE poll_id = ?";

try {
[rows] = await pool.query(sql, [pollid]);
return rows;
} catch (error) {
console.error('getPollChoices(): Database Error');
throw error;
}
}

async function getDiscreteVoteCount(choiceid) {
const sql = "SELECT COUNT(*) AS 'count' FROM discrete_polls_selections WHERE choice_id = ?";

try {
[result] = await pool.query(sql, [choiceid]);
return result[0].count;
} catch (error) {
console.error('getPollChoices(): Database Error');
throw error;
}
}

async function voteDiscretePoll(pollId, userId, choiceId){
const deleteExistingSql = "DELETE FROM discrete_polls_selections WHERE poll_id = ? AND user_id = ?"
const addVoteSql = "INSERT INTO discrete_polls_selections (poll_id, choice_id, user_id) VALUES (?, ?, ?)"

try {
// TODO: Consider making this a transaction, commit
deleteResult = await pool.query(deleteExistingSql, [pollId, userId]);
addResult = await pool.query(addVoteSql, [pollId, choiceId, userId]);
} catch (error) {
console.error('voteDiscretePoll(): Database Error');
throw error;
}

}

async function voteContinuousPoll(pollId, userId, choice){
const deleteExistingSql = "DELETE FROM continuous_poll_selections WHERE poll_id = ? AND user_id = ?"
const addVoteSql = "INSERT INTO continuous_poll_selections (poll_id, user_id, selected_value) VALUES (?, ?, ?)"

try {
// TODO: Consider making this a transaction, commit
deleteResult = await pool.query(deleteExistingSql, [pollId, userId]);
addResult = await pool.query(addVoteSql, [pollId, userId, choice]);
} catch (error) {
console.error('voteContinuousPoll(): Database Error');
throw error;
}

}

async function getContinuousPollVotes(pollId) {
const sql = "SELECT selected_value FROM continuous_poll_selections";

try {
[rows, fields] = await pool.query(sql);
return rows;
} catch (error) {
console.error('getContinuousPollVotes(): Database Error');
throw error;
}
}



module.exports = {getDiscretePolls, getContinuousPolls, getDiscretePollWithId, getContinuousPollWithId,
addDiscretePoll,addContinuousPoll, getDiscretePollChoices, getDiscreteVoteCount, voteDiscretePoll, voteContinuousPoll,
getContinuousPollVotes}

53 changes: 47 additions & 6 deletions prediction-polls/backend/src/routes/AuthorizationRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ const router = express.Router();

/**
* @swagger
* /:
* /auth/:
* get:
* tags:
* - authorization
* description: Get data after authentication. Include Header Authorization set to "BEARER {access-key}"
* responses:
* 200:
Expand All @@ -25,8 +27,10 @@ router.get('/', service.authorizeAccessToken, service.homePage)

/**
* @swagger
* /login:
* /auth/login:
* post:
* tags:
* - authorization
* description: Create session data for the user. username property can be also filled with email.
* requestBody:
* required: true
Expand Down Expand Up @@ -60,8 +64,10 @@ router.post("/login", service.logIn)

/**
* @swagger
* /access-token:
* /auth/access-token:
* post:
* tags:
* - authorization
* description: Create access token using refresh token.
* requestBody:
* required: true
Expand Down Expand Up @@ -92,8 +98,10 @@ router.post('/access-token', service.createAccessTokenFromRefreshToken)

/**
* @swagger
* /logout:
* /auth/logout:
* post:
* tags:
* - authorization
* description: Delete session data of the user
* requestBody:
* required: true
Expand All @@ -114,8 +122,10 @@ router.post('/logout', service.logOut)

/**
* @swagger
* /signup:
* /auth/signup:
* post:
* tags:
* - authorization
* description: Create new user with the given credentials. Birthday should follow format "YYYY-MM-DD"
* requestBody:
* required: true
Expand Down Expand Up @@ -143,6 +153,37 @@ router.post('/logout', service.logOut)
*/
router.post("/signup", service.signup)

router.get("/googleAuth", googleService.googleLogIn)
/**
* @swagger
* /auth/google:
* post:
* tags:
* - authorization
* description: Log in using the recieved google data. Put either googleId or code in body.
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* googleId:
* type: string
* code:
* type: string
*
* responses:
* 200:
* description: Successful response
*
* 403:
* description: Google account is not verified.
*
* 500:
* description: Server was not able to log in user with the given data.
*/
router.post("/google", googleService.googleLogIn)



module.exports = router;
Loading

0 comments on commit 10e38aa

Please sign in to comment.