CSC/ECE 517 Spring 2024 - E2424. Reimplement the Bookmarks Controller: Difference between revisions
(resized images) |
|||
(3 intermediate revisions by 2 users not shown) | |||
Line 19: | Line 19: | ||
==Implementation== | ==Implementation== | ||
===Current | ===Current vs. New Implementation=== | ||
The problems with the current implementation, which is resolved in the new implementation, is: | The problems with the current implementation, which is resolved in the new implementation, is: | ||
Line 33: | Line 33: | ||
====create==== | ====create==== | ||
<syntaxhighlight lang="ruby"> | |||
def create | def create | ||
params[:url] = params[:url].gsub!(%r{http://}, '') if params[:url].start_with?('http://') | params[:url] = params[:url].gsub!(%r{http://}, '') if params[:url].start_with?('http://') | ||
Line 48: | Line 48: | ||
redirect_to action: 'list', id: params[:topic_id] | redirect_to action: 'list', id: params[:topic_id] | ||
end | end | ||
</syntaxhighlight> | |||
* Handles URL normalization to ensure consistency in bookmark data. | * Handles URL normalization to ensure consistency in bookmark data. | ||
Line 54: | Line 55: | ||
# Controller method to create a new bookmark | # Controller method to create a new bookmark | ||
<syntaxhighlight lang="ruby"> | |||
def create | def create | ||
begin | begin | ||
Line 72: | Line 74: | ||
end | end | ||
end | end | ||
</syntaxhighlight> | |||
====update==== | ====update==== | ||
<syntaxhighlight lang="ruby"> | |||
def update | def update | ||
@bookmark = Bookmark.find(params[:id]) | @bookmark = Bookmark.find(params[:id]) | ||
Line 82: | Line 85: | ||
redirect_to action: 'list', id: @bookmark.topic_id | redirect_to action: 'list', id: @bookmark.topic_id | ||
end | end | ||
</syntaxhighlight> | |||
* Incorporates URL normalization for consistency in bookmark data. | * Incorporates URL normalization for consistency in bookmark data. | ||
* Returns JSON response with updated bookmark information for improved client-side interactions. | * Returns JSON response with updated bookmark information for improved client-side interactions. | ||
* Provides detailed error messages in case of update failure for better troubleshooting. | * Provides detailed error messages in case of update failure for better troubleshooting. | ||
<syntaxhighlight lang="ruby"> | |||
# Controller method to update an existing bookmark | # Controller method to update an existing bookmark | ||
def update | def update | ||
Line 101: | Line 105: | ||
end | end | ||
end | end | ||
</syntaxhighlight> | |||
====destroy==== | ====destroy==== | ||
<syntaxhighlight lang="ruby"> | |||
def destroy | def destroy | ||
@bookmark = Bookmark.find(params[:id]) | @bookmark = Bookmark.find(params[:id]) | ||
Line 110: | Line 115: | ||
redirect_to action: 'list', id: @bookmark.topic_id | redirect_to action: 'list', id: @bookmark.topic_id | ||
end | end | ||
</syntaxhighlight> | |||
* Utilizes structured error handling to provide informative error responses. | * Utilizes structured error handling to provide informative error responses. | ||
* Implements proper exception handling to gracefully manage record deletion errors. | * Implements proper exception handling to gracefully manage record deletion errors. | ||
* Provides clear feedback to users upon successful deletion of a bookmark. | * Provides clear feedback to users upon successful deletion of a bookmark. | ||
<syntaxhighlight lang="ruby"> | |||
# Controller method to delete a bookmark | # Controller method to delete a bookmark | ||
def destroy | def destroy | ||
Line 127: | Line 133: | ||
render json: $ERROR_INFO.to_s, status: :not_found | render json: $ERROR_INFO.to_s, status: :not_found | ||
end | end | ||
</syntaxhighlight> | |||
==Design Principles Used and Implemented== | |||
===Single Responsibility Principle (SRP)=== | |||
Each function and class within the controller adheres to the SRP, focusing on a single aspect of bookmark management to promote maintainability and clarity. For example, the `create`, `update`, `destroy`, and `list` actions in the BookmarksController are responsible for specific CRUD operations, ensuring that each method has a clear and distinct purpose. | |||
===Don't Repeat Yourself (DRY)=== | |||
Redundancy is reduced by encapsulating shared functionalities into auxiliary methods or modules, promoting code efficiency and consistency. For instance, URL normalization logic is encapsulated into a reusable method to ensure consistency across the application, reducing duplication of code and promoting maintainability. | |||
===Encapsulation=== | |||
Data and functionality are organized into suitable methods and classes to reduce dependencies and promote modularization and maintainability. For example, the `before_action :set_bookmark` method centralizes bookmark fetching for relevant actions, encapsulating this logic and reducing duplication within the controller. | |||
===Error Handling=== | |||
Robust error handling mechanisms are implemented to handle exceptions gracefully and provide informative error messages, enhancing user experience and troubleshooting capabilities. For example, structured error handling ensures that users receive clear error messages when CRUD operations fail, helping them understand and address any issues effectively. | |||
These design principles and coding patterns are instrumental in developing a robust, scalable, and maintainable bookmarks controller for the Expertiza project, ensuring high quality and reliability of the software. | |||
==Testing on Postman== | ==Testing on Postman== | ||
=== Authentication === | |||
Before testing any of these methods with Postman, submit a request to /login using the user_name and password fields, which will send an authentication token. This token must be added to Postman's 'Authorization' tab as a 'Bearer token' before any further requests can be made. | |||
Begin by sending a POST request to `/login` using the '''user_name''' and `password` fields to obtain an authentication token. | |||
[[Image:Login-postman.png | 800px | Login with provided credentials]] | |||
[[Image: | |||
In Postman, navigate to the 'Authorization' tab for your request and select 'Bearer Token'. Paste the copied token into the 'Token' field. | |||
[[Image:Postman Auth section.png | 800px | Paste token in Authorization section]] | |||
[[Image: | |||
=== CRUD Operations === | |||
[[Image:Save bookmark rating.png | 800px]] | |||
==== Create Bookmark ==== | |||
Send a POST request to the `/bookmarks` endpoint with the required parameters (`url`, `title`, `description`, `user_id`, `topic_id`). | |||
[[Image:Create Bookmark.png | 800px | Create a bookmark]] | |||
==== Read Bookmarks ==== | |||
You can retrieve a list of bookmarks associated with a particular topic ID by sending a GET request to the `/bookmarks/list/:topic_id` endpoint. | |||
[[Image:List Bookmarks.png| 800px | List bookmarks]] | |||
==== Update Bookmark ==== | |||
Send a PUT request to the `/bookmarks/:id` endpoint with the bookmark ID to update. Include the updated parameters (`url`, `title`, `description`). | |||
[[Image:Updated bookmark.png | 800px | Update a bookmark]] | |||
==== Delete Bookmark ==== | |||
Send a DELETE request to the `/bookmarks/:id` endpoint with the bookmark ID to delete. | |||
[[Image:Delete bookmark.png | 800px | Delete a bookmark]] | |||
=== Save Rating for a Bookmark === | |||
To save a rating for a bookmark, send a POST request to the `/bookmarks/:id/rate` endpoint with the bookmark ID and the rating value. | |||
[[Image:Save bookmark rating.png | 800px | Save bookmark rating]] | |||
==Github== | ==Github== | ||
Line 159: | Line 201: | ||
==Team== | ==Team== | ||
'''Contributors''' | '''Contributors''' | ||
Line 169: | Line 208: | ||
Tanay Gandhi <tgandhi@ncsu.edu><br> | Tanay Gandhi <tgandhi@ncsu.edu><br> | ||
'''Mentor''' | |||
Mohammed Ali Qureshi <mquresh@ncsu.edu> |
Latest revision as of 15:20, 27 April 2024
This page provides a description of the Expertiza based OSS project based on reimplementing the bookmarks controller.
About Expertiza
Expertiza is an open source project based on Ruby on Rails framework. Expertiza allows the instructor to create new assignments and customize new or existing assignments. It also allows the instructor to create a list of topics the students can sign up for. Students can form teams in Expertiza to work on various projects and assignments. Students can also peer review other students' submissions. Expertiza supports submission across various document types, including the URLs and wiki pages.
Problem Statement
The Expertiza application requires the reimplementation of its backend functionality for the BookmarksController. Currently, the system relies on traditional Rails architecture, but the project aims to transition to a more streamlined approach using Rails API. This transition is essential for scalability and flexibility, allowing for separate frontend and backend applications.
The BookmarksController serves as the backbone for bookmark management and user interactions within the Expertiza platform. It facilitates actions such as listing bookmarks associated with specific topics, creating new bookmarks, editing existing ones, and deleting bookmarks. Furthermore, it incorporates authorization rules to ensure users possess appropriate roles and permissions for each action.
The reimplemented BookmarksController will adhere to the Rails API structure, residing in the controller/api/v1 directory. It will maintain the existing functionality, including methods for retrieving bookmark ratings, calculating average scores for specific and total ratings, and managing strong parameters through private methods.
Implementation
Current vs. New Implementation
The problems with the current implementation, which is resolved in the new implementation, is:
1. The new implementation is designed for API use with JSON responses, improving the interaction with API clients by clearly communicating error states and messages.
2. The new controller utilizes structured error handling.
3. Introduction of before_action :set_bookmark in the new controller eliminates redundancy and enhances code reusability by centralizing bookmark fetching for relevant actions.
The current implementation and the new implementation for the CRUD operations is shown below. The new functions return a JSON object instead of rendering an HTML page.
create
def create
params[:url] = params[:url].gsub!(%r{http://}, '') if params[:url].start_with?('http://')
params[:url] = params[:url].gsub!(%r{https://}, '') if params[:url].start_with?('https://')
begin
Bookmark.create(url: create_bookmark_params[:url], title: create_bookmark_params[:title], description: create_bookmark_params[:description], user_id: session[:user].id, topic_id: create_bookmark_params[:topic_id])
ExpertizaLogger.info LoggerMessage.new(controller_name, session[:user].name, 'Your bookmark has been successfully created!', request)
flash[:success] = 'Your bookmark has been successfully created!'
rescue StandardError
ExpertizaLogger.info LoggerMessage.new(controller_name, session[:user].name, $ERROR_INFO, request)
flash[:error] = $ERROR_INFO
end
redirect_to action: 'list', id: params[:topic_id]
end
- Handles URL normalization to ensure consistency in bookmark data.
- Utilizes structured error handling for better response communication.
- Implements before_action `:set_bookmark` to centralize bookmark fetching for relevant actions.
# Controller method to create a new bookmark
def create
begin
# Normalize URL if necessary for consistency
create_bookmark_params[:url] = create_bookmark_params[:url].gsub!(%r{http://}, '') if create_bookmark_params[:url].present? && create_bookmark_params[:url].start_with?('http://')
create_bookmark_params[:url] = create_bookmark_params[:url].gsub!(%r{https://}, '') if create_bookmark_params[:url].present? && create_bookmark_params[:url].start_with?('https://')
# Attempt to save the bookmark
@bookmark = Bookmark.new(create_bookmark_params)
@bookmark.user_id = @current_user.id
@bookmark.save!
# Return JSON response with the created bookmark
render json: @bookmark, status: :created and return
rescue ActiveRecord::RecordInvalid
# Return JSON response with error message if save fails
render json: $ERROR_INFO.to_s, status: :unprocessable_entity
end
end
update
def update
@bookmark = Bookmark.find(params[:id])
@bookmark.update_attributes(url: update_bookmark_params[:bookmark][:url], title: update_bookmark_params[:bookmark][:title], description: update_bookmark_params[:bookmark][:description])
ExpertizaLogger.info LoggerMessage.new(controller_name, session[:user].name, 'Your bookmark has been successfully updated!', request)
flash[:success] = 'Your bookmark has been successfully updated!'
redirect_to action: 'list', id: @bookmark.topic_id
end
- Incorporates URL normalization for consistency in bookmark data.
- Returns JSON response with updated bookmark information for improved client-side interactions.
- Provides detailed error messages in case of update failure for better troubleshooting.
# Controller method to update an existing bookmark
def update
# Normalize URL if necessary for consistency
update_bookmark_params[:url] = update_bookmark_params[:url].gsub!(%r{http://}, '') if update_bookmark_params[:url].start_with?('http://')
update_bookmark_params[:url] = update_bookmark_params[:url].gsub!(%r{https://}, '') if update_bookmark_params[:url].start_with?('https://')
# Attempt to update the bookmark
if @bookmark.update(update_bookmark_params)
# Return JSON response with updated bookmark if successful
render json: @bookmark, status: :ok
else
# Return JSON response with error messages if update fails
render json: @bookmark.errors.full_messages, status: :unprocessable_entity
end
end
destroy
def destroy
@bookmark = Bookmark.find(params[:id])
@bookmark.destroy
ExpertizaLogger.info LoggerMessage.new(controller_name, session[:user].name, 'Your bookmark has been successfully deleted!', request)
flash[:success] = 'Your bookmark has been successfully deleted!'
redirect_to action: 'list', id: @bookmark.topic_id
end
- Utilizes structured error handling to provide informative error responses.
- Implements proper exception handling to gracefully manage record deletion errors.
- Provides clear feedback to users upon successful deletion of a bookmark.
# Controller method to delete a bookmark
def destroy
# Find the bookmark to delete
@bookmark = Bookmark.find(params[:id])
# Attempt to delete the bookmark
@bookmark.destroy
# Return JSON response indicating successful deletion
render json: { message: 'Bookmark successfully deleted' }, status: :ok
rescue ActiveRecord::RecordNotFound
# Return JSON response with error message if bookmark not found
render json: $ERROR_INFO.to_s, status: :not_found
end
Design Principles Used and Implemented
Single Responsibility Principle (SRP)
Each function and class within the controller adheres to the SRP, focusing on a single aspect of bookmark management to promote maintainability and clarity. For example, the `create`, `update`, `destroy`, and `list` actions in the BookmarksController are responsible for specific CRUD operations, ensuring that each method has a clear and distinct purpose.
Don't Repeat Yourself (DRY)
Redundancy is reduced by encapsulating shared functionalities into auxiliary methods or modules, promoting code efficiency and consistency. For instance, URL normalization logic is encapsulated into a reusable method to ensure consistency across the application, reducing duplication of code and promoting maintainability.
Encapsulation
Data and functionality are organized into suitable methods and classes to reduce dependencies and promote modularization and maintainability. For example, the `before_action :set_bookmark` method centralizes bookmark fetching for relevant actions, encapsulating this logic and reducing duplication within the controller.
Error Handling
Robust error handling mechanisms are implemented to handle exceptions gracefully and provide informative error messages, enhancing user experience and troubleshooting capabilities. For example, structured error handling ensures that users receive clear error messages when CRUD operations fail, helping them understand and address any issues effectively.
These design principles and coding patterns are instrumental in developing a robust, scalable, and maintainable bookmarks controller for the Expertiza project, ensuring high quality and reliability of the software.
Testing on Postman
Authentication
Before testing any of these methods with Postman, submit a request to /login using the user_name and password fields, which will send an authentication token. This token must be added to Postman's 'Authorization' tab as a 'Bearer token' before any further requests can be made.
Begin by sending a POST request to `/login` using the user_name and `password` fields to obtain an authentication token.
In Postman, navigate to the 'Authorization' tab for your request and select 'Bearer Token'. Paste the copied token into the 'Token' field.
CRUD Operations
Create Bookmark
Send a POST request to the `/bookmarks` endpoint with the required parameters (`url`, `title`, `description`, `user_id`, `topic_id`).
Read Bookmarks
You can retrieve a list of bookmarks associated with a particular topic ID by sending a GET request to the `/bookmarks/list/:topic_id` endpoint.
Update Bookmark
Send a PUT request to the `/bookmarks/:id` endpoint with the bookmark ID to update. Include the updated parameters (`url`, `title`, `description`).
Delete Bookmark
Send a DELETE request to the `/bookmarks/:id` endpoint with the bookmark ID to delete.
Save Rating for a Bookmark
To save a rating for a bookmark, send a POST request to the `/bookmarks/:id/rate` endpoint with the bookmark ID and the rating value.
Github
Repository: https://github.com/akshat22/reimplementation-back-end
Pull Request: https://github.com/expertiza/reimplementation-back-end/pull/76
Team
Contributors
Akshat Nitin Savla <asavla@ncsu.edu>
Mitanshu Reshamwala <mresham@ncsu.edu>
Tanay Gandhi <tgandhi@ncsu.edu>
Mentor
Mohammed Ali Qureshi <mquresh@ncsu.edu>