create_pokemon_from_base64_service.rb 865 B

1234567891011121314151617181920212223242526272829303132333435
  1. # frozen_string_literal: true
  2. require './lib/api_error/base_error'
  3. class CreatePokemonFromBase64Service < BaseService
  4. def execute(base64_encoded_pokemon)
  5. response = client.parse_base64(base64_encoded_pokemon)
  6. pokemon = ::Pokemon.transaction do
  7. ::Pokemon.create!(response.pokemon.map(&:to_h))
  8. end
  9. success(pokemon)
  10. rescue PKParse::Error => e
  11. error(APIError::BaseError.new(e.message, internal_error: e))
  12. rescue ActiveRecord::ActiveRecordError => e
  13. msg = "Failed to commit parsed results: #{e}\n#{e.backtrace.join("\n")}"
  14. PKParse.logger.error(msg)
  15. error(APIError::BaseError.new(
  16. 'Failed to commit the uploaded pokemon.',
  17. internal_error: e,
  18. ))
  19. end
  20. private
  21. def success(pokemon)
  22. super().merge(pokemon: pokemon)
  23. end
  24. def client
  25. @client ||= PKParse::Client.new
  26. end
  27. end