Skip to content

Commit

Permalink
feature/1-init-project
Browse files Browse the repository at this point in the history
  • Loading branch information
ChinhQuoc committed Sep 8, 2024
1 parent 7d64e39 commit c63307e
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 26 deletions.
10 changes: 10 additions & 0 deletions backend/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import os
from flaskr import create_app

os.environ['FLASK_APP'] = 'flaskr:create_app'
os.environ['FLASK_ENV'] = 'development'

app = create_app()

if __name__ == '__main__':
app.run()
41 changes: 41 additions & 0 deletions backend/flaskr/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,39 @@ def create_app(test_config=None):
"""
@TODO: Set up CORS. Allow '*' for origins. Delete the sample route after completing the TODOs
"""
#CORS(app, resources={r"*/api/*" : {origins: '*'}})

CORS(app)

"""
@TODO: Use the after_request decorator to set Access-Control-Allow
"""
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Headers', 'Content-Type, Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS')
return response

"""
@TODO:
Create an endpoint to handle GET requests
for all available categories.
"""
@app.route('/categories')
def get_categories():
# Implement pagination
page = request.args.get('page', 1, type=int)
start = (page - 1) * 10
end = start + 10

categories = Category.query.all()
formatted_categories = [category.format() for category in categories]

return jsonify({
'success': True,
'categories': formatted_categories[start:end],
'total_categories': len(formatted_categories)
})

"""
@TODO:
Expand All @@ -45,6 +67,25 @@ def create_app(test_config=None):
ten questions per page and pagination at the bottom of the screen for three pages.
Clicking on the page numbers should update the questions.
"""
@app.route('/questions')
def get_questions():
# Implement pagination
page = request.args.get('page', 1, type=int)
start = (page - 1) * 10
end = start + 10

categories = Category.query.all()
formatted_categories = [category.format() for category in categories]

questions = Question.query.all()
formatted_questions = [question.format() for question in questions]

return jsonify({
'success': True,
'questions': formatted_questions[start:end],
'total_questions': len(formatted_questions),
'categories': formatted_categories,
})

"""
@TODO:
Expand Down
5 changes: 3 additions & 2 deletions backend/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import json

database_name = 'trivia'
database_path = 'postgresql://{}/{}'.format('localhost:5432', database_name)
database_path = 'postgresql://postgres:12345@{}/{}'.format('localhost:5432', database_name)

db = SQLAlchemy()

Expand All @@ -17,7 +17,8 @@ def setup_db(app, database_path=database_path):
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.app = app
db.init_app(app)
db.create_all()
with app.app_context():
db.create_all()

"""
Question
Expand Down
48 changes: 24 additions & 24 deletions frontend/src/components/QuestionView.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import React, { Component } from 'react';
import '../stylesheets/App.css';
import Question from './Question';
import Search from './Search';
import $ from 'jquery';
import React, { Component } from "react";
import "../stylesheets/App.css";
import Question from "./Question";
import Search from "./Search";
import $ from "jquery";

class QuestionView extends Component {
constructor() {
Expand All @@ -23,18 +23,18 @@ class QuestionView extends Component {
getQuestions = () => {
$.ajax({
url: `/questions?page=${this.state.page}`, //TODO: update request URL
type: 'GET',
type: "GET",
success: (result) => {
this.setState({
questions: result.questions,
totalQuestions: result.total_questions,
categories: result.categories,
currentCategory: result.current_category,
// currentCategory: result.current_category,
});
return;
},
error: (error) => {
alert('Unable to load questions. Please try your request again');
alert("Unable to load questions. Please try your request again");
return;
},
});
Expand All @@ -51,7 +51,7 @@ class QuestionView extends Component {
pageNumbers.push(
<span
key={i}
className={`page-num ${i === this.state.page ? 'active' : ''}`}
className={`page-num ${i === this.state.page ? "active" : ""}`}
onClick={() => {
this.selectPage(i);
}}
Expand All @@ -66,7 +66,7 @@ class QuestionView extends Component {
getByCategory = (id) => {
$.ajax({
url: `/categories/${id}/questions`, //TODO: update request URL
type: 'GET',
type: "GET",
success: (result) => {
this.setState({
questions: result.questions,
Expand All @@ -76,7 +76,7 @@ class QuestionView extends Component {
return;
},
error: (error) => {
alert('Unable to load questions. Please try your request again');
alert("Unable to load questions. Please try your request again");
return;
},
});
Expand All @@ -85,9 +85,9 @@ class QuestionView extends Component {
submitSearch = (searchTerm) => {
$.ajax({
url: `/questions`, //TODO: update request URL
type: 'POST',
dataType: 'json',
contentType: 'application/json',
type: "POST",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({ searchTerm: searchTerm }),
xhrFields: {
withCredentials: true,
Expand All @@ -102,23 +102,23 @@ class QuestionView extends Component {
return;
},
error: (error) => {
alert('Unable to load questions. Please try your request again');
alert("Unable to load questions. Please try your request again");
return;
},
});
};

questionAction = (id) => (action) => {
if (action === 'DELETE') {
if (window.confirm('are you sure you want to delete the question?')) {
if (action === "DELETE") {
if (window.confirm("are you sure you want to delete the question?")) {
$.ajax({
url: `/questions/${id}`, //TODO: update request URL
type: 'DELETE',
type: "DELETE",
success: (result) => {
this.getQuestions();
},
error: (error) => {
alert('Unable to load questions. Please try your request again');
alert("Unable to load questions. Please try your request again");
return;
},
});
Expand All @@ -128,8 +128,8 @@ class QuestionView extends Component {

render() {
return (
<div className='question-view'>
<div className='categories-list'>
<div className="question-view">
<div className="categories-list">
<h2
onClick={() => {
this.getQuestions();
Expand All @@ -147,7 +147,7 @@ class QuestionView extends Component {
>
{this.state.categories[id]}
<img
className='category'
className="category"
alt={`${this.state.categories[id].toLowerCase()}`}
src={`${this.state.categories[id].toLowerCase()}.svg`}
/>
Expand All @@ -156,7 +156,7 @@ class QuestionView extends Component {
</ul>
<Search submitSearch={this.submitSearch} />
</div>
<div className='questions-list'>
<div className="questions-list">
<h2>Questions</h2>
{this.state.questions.map((q, ind) => (
<Question
Expand All @@ -168,7 +168,7 @@ class QuestionView extends Component {
questionAction={this.questionAction(q.id)}
/>
))}
<div className='pagination-menu'>{this.createPagination()}</div>
<div className="pagination-menu">{this.createPagination()}</div>
</div>
</div>
);
Expand Down

0 comments on commit c63307e

Please sign in to comment.