Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package either
- import java.util.UUID
- import external.{ExternalLocation, GoogleLocation}
- import model.{Coordinates, Location}
- /**
- * @author Alexander Isakov
- */
- trait LocationService {
- protected val googleLocationService: GoogleLocationService
- //
- def get(normalizedName: String, coordinate: Coordinates): Option[Location]
- def get(placeId: String): Option[Location]
- def create(el: ExternalLocation): Either[CreateLocationError, Location] = {
- (for {
- c <- el.coordinates
- _ <- get(normalize(el.name), c)
- } yield ()).fold(for {
- address <- el.address
- .map(a => a.trim)
- .filter(a => a.nonEmpty)
- .toRight(InvalidLocationArgumentsError)
- gl <- googleLocationService
- .getByAddress(s"${el.name} $address")
- .left
- .map {
- case ConnectionError => RetryLaterError
- case GoogleLocationNotFoundError => InvalidLocationArgumentsError
- }
- result <- get(gl.placeId)
- .fold(Option(create(toLocation(el.name, gl))))(_ => None)
- .toRight(DuplicateLocationException)
- } yield result)(_ => Left(InvalidLocationArgumentsError))
- }
- //
- protected def create(location: Location): Location
- protected def toLocation(name: String, gl: GoogleLocation): Location = {
- Location(UUID.randomUUID(), gl.placeId, name, normalize(name), gl.formattedAddress, gl.coordinates)
- }
- protected def normalize(s: String): String = {
- s.replaceAll("[^\\p{L}\\p{Nd}]+", "").toLowerCase
- }
- }
- sealed trait CreateLocationError
- case object InvalidLocationArgumentsError extends CreateLocationError
- case object DuplicateLocationException extends CreateLocationError
- case object RetryLaterError extends CreateLocationError
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement