CPT Requirements
CPT Requirements
Requirement 1: Input Instructions
Function requires user to input comment text in order to add a comment to the book.
function addComment() {
const commentInput = document.getElementById('commentInput');
const commentText = commentInput.value.trim();
if (commentText === '') {
alert('Comment cannot be empty.');
return;
}
List
The variable comment is a list, and it contains dictionaries where each comment is one dictionary that contains keys like book_id, comment_text, and user_id and their corresponding values. e
def initComments():
comments = [
{
"book_id": 1, # Reference to the book with ID 1 (ensure the book exists)
"comment_text": "I loved this book!",
"user_id": 1, # Reference to the user with ID 1 (ensure the user exists)
},
{
"book_id": 2,
"comment_text": "This was an amazing read! Highly recommend.",
"user_id": 1,
},
{
"book_id": 4, # Reference to the book with ID 1
"comment_text": "Really insightful. The chapters on his inventions were fantastic.",
"user_id": 1, # Reference to the user with ID 1
}
]
Procedure
def update(self, inputs):
if not isinstance(inputs, dict):
return self
book_id = inputs.get("book_id", None)
user_id = inputs.get("user_id", None)
comment_text = inputs.get("comment_text", "")
if book_id:
self.book_id = book_id
if user_id:
self.user_id = user_id
if comment_text:
self.comment_text = comment_text
try:
db.session.commit()
except IntegrityError as e:
db.session.rollback()
print(f"IntegrityError occurred: {e}")
return None
return self
- Purpose: Update comments
- Name: Update
- Return type: Not necessary
- Parameter: input
Algorithm with sequencing, selection, and iteration
def get_comments_for_book(book_id=None):
if book_id:
comments_query = Comments.query.filter_by(book_id=book_id).all()
else:
comments_query = Comments.query.all()
comments_data = []
for comment in comments_query:
user = User.query.get(comment.user_id) # Fetch the user using the user_id
user_name = user._name if user else "Unknown User" # Fetch the name
comments_data.append({
"id": comment.id,
"book_id": comment.book_id,
"user_id": comment.user_id, # Keep user_id
"user_name": user_name, # Add the user_name
"comment_text": comment.comment_text
})
return comments_data
- Sequencing: checking if book_id is provided, then querying the database, fetching users, and appending the data into a list.
- Selection: Yes, the if book_id: statement is a selection (conditional statement). If a book_id is provided, it queries for comments specific to that book; otherwise, it queries for all comments.
- Iteration: Yes, the for comment in comments_query: loop is an iteration. It goes through each comment in the comments_query and processes it, fetching associated user information and appending it to the comments_data list.
Call to my student-developed procedure
@bookreview_api.route('/comments', methods=['GET', 'POST'])
def manage_comments():
if request.method == 'GET':
book_id = request.args.get('book_id')
if not book_id:
return jsonify({'error': 'Book ID is required'}), 400
comments = get_comments_for_book(book_id)
if comments:
return jsonify({'comments': comments})
else:
return jsonify({'message': 'No comments found for this book'}), 404
Gets a random book. If it’s a valid book id, it calls the get_comments_for_book function which will retrieve the associated comments, otherwise it will return a “no comments found” message.
Instructions for output
The outputs are the comments, organized by username and comment text.
function displayComments(comments) {
const commentsList = document.getElementById('commentsList');
commentsList.innerHTML = ''; // Clear previous comments
comments.forEach(comment => {
fetchUserName(comment.user_id).then(username => {
const commentDiv = document.createElement('div');
commentDiv.classList.add('comment-box');
commentDiv.innerHTML = `
<div class="comment-text" id="comment-${comment.id}">
<strong>${username}</strong><br>
<span class="comment-text-display" data-comment-id="${comment.id}">${comment.comment_text}</span>
<!-- Pencil icon to update the comment -->
<button class="update-comment" data-comment-id="${comment.id}">📝</button>
<!-- Trash can button to delete the comment -->
<button class="delete-comment" data-comment-id="${comment.id}">🗑️</button>
</div>
`;
commentsList.appendChild(commentDiv);
});
});