Advertisement
Guest User

Untitled

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