Advertisement
Guest User

Untitled

a guest
Jan 9th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.78 KB | None | 0 0
  1. package either
  2.  
  3. import java.util.UUID
  4.  
  5. import external.{ExternalLocation, GoogleLocation}
  6. import model.{Coordinates, Location}
  7.  
  8. /**
  9.   * @author Alexander Isakov
  10.   */
  11. trait LocationService {
  12.  
  13.   protected val googleLocationService: GoogleLocationService
  14.  
  15.   //
  16.  
  17.   def get(normalizedName: String, coordinate: Coordinates): Option[Location]
  18.  
  19.   def get(placeId: String): Option[Location]
  20.  
  21.   def create(el: ExternalLocation): Either[CreateLocationError, Location] = {
  22.     (for {
  23.       c <- el.coordinates
  24.       _ <- get(normalize(el.name), c)
  25.     } yield ()).fold(for {
  26.       address <- el.address
  27.         .map(a => a.trim)
  28.         .filter(a => a.nonEmpty)
  29.         .toRight(InvalidLocationArgumentsError)
  30.  
  31.       gl <- googleLocationService
  32.         .getByAddress(s"${el.name} $address")
  33.         .left
  34.         .map {
  35.           case ConnectionError             => RetryLaterError
  36.           case GoogleLocationNotFoundError => InvalidLocationArgumentsError
  37.         }
  38.  
  39.       result <- get(gl.placeId)
  40.         .fold(Option(create(toLocation(el.name, gl))))(_ => None)
  41.         .toRight(DuplicateLocationException)
  42.     } yield result)(_ => Left(InvalidLocationArgumentsError))
  43.   }
  44.  
  45.   //
  46.  
  47.   protected def create(location: Location): Location
  48.  
  49.   protected def toLocation(name: String, gl: GoogleLocation): Location = {
  50.     Location(UUID.randomUUID(), gl.placeId, name, normalize(name), gl.formattedAddress, gl.coordinates)
  51.   }
  52.  
  53.   protected def normalize(s: String): String = {
  54.     s.replaceAll("[^\\p{L}\\p{Nd}]+", "").toLowerCase
  55.   }
  56.  
  57. }
  58.  
  59. sealed trait CreateLocationError
  60. case object InvalidLocationArgumentsError extends CreateLocationError
  61. case object DuplicateLocationException    extends CreateLocationError
  62. case object RetryLaterError               extends CreateLocationError
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement