| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- # frozen_string_literal: true
- require './lib/pkparse/client'
- class API::V1::PokemonController < API::V1::ApplicationController
- def create
- @pokemon = Pokemon.new(new_pokemon_params)
- unless @pokemon.save
- @error = APIError::BaseError.new('Failed to create pokemon.')
- render partial: 'error', status: :unprocessable_entity
- end
- end
- def destroy
- @pokemon = Pokemon.find(params[:id])
- if @pokemon.destroy
- render :show
- else
- @error = APIError::BaseError.new('Failed to delete pokemon.')
- render partial: 'error', status: :unprocessable_entity
- end
- end
- def index
- @pokemon = Pokemon.all
- end
- def show
- @pokemon = Pokemon.find_by(id: params[:id])
- unless @pokemon
- @error = APIError::BaseError.new("Pokemon with 'id'=#{params[:id]} was not found.")
- render partial: 'error', status: :not_found
- end
- end
- def upload
- files = params[:pokemon]
- response = pkparse_client.parse(files)
- Pokemon.transaction do
- @pokemon = Pokemon.create!(response.pokemon.map(&:to_h))
- end
- render :index
- rescue PKParse::Error => e
- @error = APIError::BaseError.new(e.message, internal_error: e)
- render partial: 'error', status: :unprocessable_entity
- rescue ActiveRecord::ActiveRecordError => e
- PKParse.logger.error("Failed to commit parsed results: #{e}\n#{e.backtrace.join("\n")}")
- @error = APIError::BaseError.new('Failed to commit the uploaded pokemon.', internal_error: e)
- render partial: 'error', status: :unprocessable_entity
- end
- private
- def new_pokemon_params
- params.require(:pokemon).permit(
- :id, :pokedex_number, :nickname
- )
- end
- def pkparse_client
- # There may be some configuration we'll provide in the future that would
- # benefit from instantiating the client in this way
- @pkparse_client ||= PKParse::Client.new
- end
- end
|