Created
March 26, 2019 17:43
-
-
Save kazzkiq/70438828daae09c91ae36849ee35d994 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Endpoints::Bookmarks::Update | |
include Onyx::HTTP::Endpoint | |
params do | |
path do | |
type id : Int32 | |
end | |
json require: true do | |
type id_category : Int32? | |
type description : String? | |
end | |
end | |
errors do | |
# Return 400 if there is nothing to update | |
type NothingToUpdate(400) | |
# Return 404 if item is not found | |
type ItemNotFound(404) | |
end | |
def call | |
# If nothing passed in body, no update occurs | |
raise NothingToUpdate.new if params.json.id_category.nil? && params.json.description.nil? | |
# Fetch the item from DB | |
entity = Onyx.query(Models::Bookmark.where(id: params.path.id)).first? | |
raise ItemNotFound.new unless entity | |
# Create a new changeset with a snapshot of actual entity's values | |
changeset = entity.changeset | |
unless params.json.id_category.nil? | |
category : Int32 = params.json.id_category || 0 | |
changeset.update(id_category: category) | |
end | |
unless params.json.description.nil? | |
changeset.update(description: params.json.description) | |
end | |
# Halt if there are no actual changes | |
raise NothingToUpdate.new if changeset.empty? | |
# Update the date_modified field | |
changeset.update(date_modified: Time.now) | |
# Update the item with modified changeset | |
Onyx.query(entity.update(changeset)) | |
return status(204) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment