Skip to content

Commit

Permalink
add logic submitAnswer in api, refactor completeSentence b00tc4mp#182
Browse files Browse the repository at this point in the history
  • Loading branch information
AgusBirman committed Aug 7, 2024
1 parent 688c75b commit ed1dc70
Show file tree
Hide file tree
Showing 14 changed files with 210 additions and 29 deletions.
6 changes: 5 additions & 1 deletion staff/agustin-birman/api/handlers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import getExcercisesHandler from './getExcercisesHandler.js'
import deleteExcerciseHandler from './deleteExcerciseHandler.js'
import editExcerciseHandler from './editExcerciseHandler.js'

import submitAnswer from '../logic/submitAnswer.js'

export {
registerUserHandler,
authenticateUserHandler,
Expand All @@ -31,5 +33,7 @@ export {

getExcercisesHandler,
deleteExcerciseHandler,
editExcerciseHandler
editExcerciseHandler,

submitAnswer
}
22 changes: 22 additions & 0 deletions staff/agustin-birman/api/handlers/submitAnswerHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import logic from '../logic/index.js'
import jwt from '../util/jsonwebtoken-promised.js'

const { JWT_SECRET } = process.env

export default (req, res, next) => {
try {
const token = req.headers.authorization.slice(7)

const { exerciseId, answer } = req.body
jwt.verify(token, JWT_SECRET)
try {
logic.submitAnswer(userId, exerciseId, answer)
.then(() => res.status(201).json())
.catch(error => next(error))
} catch (error) {
next(error)
}
} catch (error) {
next(error)
}
}
5 changes: 4 additions & 1 deletion staff/agustin-birman/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import {
getExcercisesHandler,
deleteExcerciseHandler,
editActivityHandler,
editExcerciseHandler
editExcerciseHandler,
submitAnswer
} from './handlers/index.js'

const { MONGODB_URL, PORT } = process.env
Expand Down Expand Up @@ -60,6 +61,8 @@ mongoose.connect(MONGODB_URL)

api.patch('/excercise/:excerciseId', jsonBodyParser, editExcerciseHandler)

api.post('/answer', jsonBodyParser, submitAnswer)

api.use(errorHandler)

api.listen(PORT, () => console.log(`API is running on PORT ${PORT}`))
Expand Down
31 changes: 31 additions & 0 deletions staff/agustin-birman/api/logic/createActivity.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import 'dotenv/config'
import mongoose from 'mongoose'
import bcrypt from 'bcryptjs'

import { expect } from 'chai'

import { User, Activity } from '../data/index.js'
import { ContentError, CredentialsError } from 'com/errors.js'

import createActivity from './createActivity.js'

const { MONGODB_URL_TEST } = process.env

describe('createActivity', () => {
before(() => mongoose.connect(MONGODB_URL_TEST))

beforeEach(() => Promise.all([User.deleteMany(), Activity.deleteMany()]))

it('succeds on creating activity', () =>
bcrypt.hash('123123123', 8)
.then(hash => User.create({ name: 'Mac', surname: 'Book', email: '[email protected]', username: 'macbook', password: hash, userType: 'teacher' }))
.then(user =>
createActivity(user.id, 'Hola', 'Pepe')
.then(() => Activity.findOne())
.then(activity => {
expect(activity.title).to.equal('Hola')
expect(activity.description).to.equal('Pepe')
})
)
)
})
5 changes: 4 additions & 1 deletion staff/agustin-birman/api/logic/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import getExcercises from './getExcercises.js'
import deleteExcercise from './deleteExcercise.js'
import editExcercise from './editExcercise.js'

import submitAnswer from './submitAnswer.js'

const logic = {
registerUser,
authenticateUser,
Expand All @@ -23,7 +25,8 @@ const logic = {
deleteActivity,
getExcercises,
deleteExcercise,
editExcercise
editExcercise,
submitAnswer
}

export default logic
2 changes: 1 addition & 1 deletion staff/agustin-birman/api/logic/registerUser.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ mongoose.connect(MONGODB_URL)
} catch (error) {
console.error(error)
}
}).catch(error => { console.log(error) })
}).catch(error => { console.error(error) })
41 changes: 41 additions & 0 deletions staff/agustin-birman/api/logic/submitAnswer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import validate from "com/validate.js";
import { User, Answer, Excercise } from "../data/index.js";
import { NotFoundError, SystemError } from "com/errors.js";

const submitAnswer = (userId, excerciseId, answer) => {
validate.id(userId, 'userId')
validate.id(excerciseId, 'excerviseId')
validate.text(answer, 'answer')

return User.findById(userId).lean()
.catch(error => { throw new SystemError(error.message) })
.then(user => {
if (!user)
throw new NotFoundError('user not found')

return Excercise.findById(excerciseId).lean()
.catch(error => { throw new SystemError(error.message) })
.then(excercise => {
if (!excercise)
throw new NotFoundError('excercise not found')

const newAnswer = {
student: userId,
exercise: excerciseId,
answer
}

return Answer.create(newAnswer)
.catch(error => { throw new SystemError(error.message) })
.then(answer => {
answer.id = answer._id.toString()

delete answer._id

return answer.id
})
})
})
}

export default submitAnswer
17 changes: 17 additions & 0 deletions staff/agustin-birman/api/logic/submitAnswer.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import 'dotenv/config'
import mongoose from 'mongoose'
import submitAnswer from './submitAnswer.js'

const { MONGODB_URL } = process.env

mongoose.connect(MONGODB_URL)
.then(() => {
try {
submitAnswer('66a94dcb34505782bcd8cfd0', '66b1cdc7debd28877917c736', 'hat')
.then(() => console.log('answer submitted'))
.catch(error => console.error(error))
} catch (error) {
console.error(error)
}
})
.catch(error => console.error(error))
10 changes: 7 additions & 3 deletions staff/agustin-birman/app/src/views/Home.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@ import logic from '../logic'
import SelectActivity from './components/SelectActivity'
import MenuItem from './components/MenuItems'
import CompleteSentenceInfo from './components/CompleteSentenceInfo'
import CreateCompleteSentence from './components/CreateCompleteSentence'
import CompleteSentence from './components/CompleteSentence'
import CreateActivity from './components/CreateActivity'
import ListActivities from './components/ListActivities'
import ViewActivity from './components/ViewActivity'
import ListExcercises from './components/ListExcercises'
import DoActivity from './components/DoActivity'

function Home() {
const [name, setName] = useState('')
Expand Down Expand Up @@ -54,14 +55,17 @@ function Home() {
<Route path="/" element={<MenuItem></MenuItem>} />
<Route path="/activities/select-type" element={<SelectActivity></SelectActivity>} />

<Route path="/activities/info-complete-sentence" element={<CompleteSentenceInfo></CompleteSentenceInfo>} />
<Route path="/activities/create" element={<CreateActivity></CreateActivity>} />
<Route path="/activities/:activityId/create-complete-sentence-excercise" element={<CreateCompleteSentence></CreateCompleteSentence>} />

<Route path="/activities/info-complete-sentence" element={<CompleteSentenceInfo></CompleteSentenceInfo>} />
<Route path="/activities/:activityId/complete-sentence-excercise" element={<CompleteSentence></CompleteSentence>} />

<Route path="/activities/list" element={<ListActivities></ListActivities>} />

<Route path="/activities/:activityId" element={<ViewActivity></ViewActivity>} />
<Route path="/activities/:activityId/excercises" element={<ListExcercises></ListExcercises>} />

<Route path="/activities/:activityId/do-activity" element={<DoActivity></DoActivity>} />
</Routes>
</View>
</View>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,18 @@ function CreateCompleteSentence() {
loadExcercises()
, [])

useEffect(() => {
if (sentence) {
const removeAnswer = sentence.match(ANSWER_REGEX)

if (removeAnswer && removeAnswer[1])
setAnswerInput(removeAnswer[1])
else
setAnswerInput('Not answer found')
}
}
, [editView])

const loadExcercises = () => {
try {
logic.getExcercises(activityId)
Expand All @@ -45,26 +57,6 @@ function CreateCompleteSentence() {
}
}

// const handleCreatedExercise = () => {
// const form = document.querySelector('form');

// const sentence = form.sentence.value

// try {
// logic.createCompleteSentenceExcercise(activityId, sentence)
// .then(() => navigate('/'))
// .catch(error => {
// console.error(error)

// setMessage(error.message)
// })
// } catch (error) {
// console.error(error)

// setMessage(error.message)
// }
// }

const handleDeletedExcericise = (excerciseId) => {
try {
logic.deleteExcercise(excerciseId)
Expand Down
64 changes: 64 additions & 0 deletions staff/agustin-birman/app/src/views/components/DoActivity/index.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { useParams } from "react-router-dom";
import View from "../../../components/library/View";
import { useEffect, useState } from "react";
import Heading from "../../../components/core/Heading";
import Text from "../../../components/core/Text";
import logic from "../../../logic";
import Input from "../../../components/core/Input";

let SENTENCE_REGEX = /^(.*?)\s*\(.*?\)\s*(.*?)$/

function DoActivity() {
const [exercises, setExercises] = useState([])
const { activityId } = useParams()

useEffect(() => {
loadExcercises()
}, [])

const loadExcercises = () => {
try {
logic.getExcercises(activityId)
.then(exercises => setExercises(exercises))
.catch(error => {
console.error(error)

alert(error.message) //TODO hacer un alert mejor
})
} catch (error) {
console.error(error)

alert(error.message)
}
}

const handleSubmittedAnswer = () => {
//TODO
}

return (<View>
<Heading level='2'></Heading>
{exercises.map(exercise => {
let beforeParentheses = ''
let afterParentheses = ''

let matches = exercise.sentence.match(SENTENCE_REGEX);

if (matches) {
beforeParentheses = matches[1].trim()
afterParentheses = matches[2].trim()
}

return (<View key={exercise.index}>
<Text>{exercise.index + 1} Exercise</Text>
<Text>{beforeParentheses}</Text>
<Input />
<Text>{afterParentheses}</Text>
</View>)
}
)}
</View >
)
}

export default DoActivity
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ function ListExcercises() {
</div>
</div>
)}
<Button><Link to={`/activities/${activityId}/create-complete-sentence-excercise`}>Add a new excercise</Link></Button>
<Button><Link to={`/activities/${activityId}/complete-sentence-excercise`}>Add a new excercise</Link></Button>
<Button><Link to={`/activities/${activityId}`}>Go back</Link></Button>
</div>
</View >
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ function ViewActivity() {
<Button onClick={handleDeleteActivity}>Delete Activity</Button>
<Button onClick={handleEditButton}>Edit Activity</Button>
<Button><Link to={`/activities/${activityId}/excercises`}>List Excercises</Link></Button>
<Button>Start Activity</Button>
<Button><Link to={`/activities/${activityId}/do-activity`}>Start Activity</Link></Button>
</>
: <>
<Button onClick={handleEditButton}>Cancel Edit</Button>
Expand Down

0 comments on commit ed1dc70

Please sign in to comment.