pokemon_controller.rb 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # frozen_string_literal: true
  2. require './lib/pkparse/client'
  3. class API::V1::PokemonController < API::V1::ApplicationController
  4. def create
  5. @pokemon = Pokemon.new(new_pokemon_params)
  6. unless @pokemon.save
  7. @error = APIError::BaseError.new('Failed to create pokemon.')
  8. render partial: 'error', status: :unprocessable_entity
  9. end
  10. end
  11. def destroy
  12. @pokemon = Pokemon.find(params[:id])
  13. if @pokemon.destroy
  14. render :show
  15. else
  16. @error = APIError::BaseError.new('Failed to delete pokemon.')
  17. render partial: 'error', status: :unprocessable_entity
  18. end
  19. end
  20. def index
  21. @pokemon = Pokemon.all
  22. end
  23. def show
  24. @pokemon = Pokemon.find_by(id: params[:id])
  25. unless @pokemon
  26. @error = APIError::BaseError.new("Pokemon with 'id'=#{params[:id]} was not found.")
  27. render partial: 'error', status: :not_found
  28. end
  29. end
  30. def upload
  31. files = params[:pokemon]
  32. response = pkparse_client.parse(files)
  33. Pokemon.transaction do
  34. @pokemon = Pokemon.create!(response.pokemon.map(&:to_h))
  35. end
  36. render :index
  37. rescue PKParse::Error => e
  38. @error = APIError::BaseError.new(e.message, internal_error: e)
  39. render partial: 'error', status: :unprocessable_entity
  40. rescue ActiveRecord::ActiveRecordError => e
  41. PKParse.logger.error("Failed to commit parsed results: #{e}\n#{e.backtrace.join("\n")}")
  42. @error = APIError::BaseError.new('Failed to commit the uploaded pokemon.', internal_error: e)
  43. render partial: 'error', status: :unprocessable_entity
  44. end
  45. private
  46. def new_pokemon_params
  47. params.require(:pokemon).permit(
  48. :id, :pokedex_number, :nickname
  49. )
  50. end
  51. def pkparse_client
  52. # There may be some configuration we'll provide in the future that would
  53. # benefit from instantiating the client in this way
  54. @pkparse_client ||= PKParse::Client.new
  55. end
  56. end