-
Notifications
You must be signed in to change notification settings - Fork 29
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(scala): browse helpers (generated)
algolia/api-clients-automation#4062 Co-authored-by: Thomas Raffray <[email protected]>
- Loading branch information
1 parent
6b96325
commit 4183dc5
Showing
2 changed files
with
176 additions
and
3 deletions.
There are no files selected for viewing
46 changes: 46 additions & 0 deletions
46
src/main/scala/algoliasearch/extension/internal/Iterable.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package algoliasearch.extension.internal | ||
|
||
import scala.concurrent.{ExecutionContext, Future, blocking} | ||
import scala.concurrent.duration.Duration | ||
|
||
private[algoliasearch] object Iterable { | ||
case class Error[T]( | ||
validate: T => Boolean, | ||
message: Option[T => String] = None | ||
) | ||
|
||
def createIterable[T]( | ||
execute: Option[T] => Future[T], | ||
validate: T => Boolean, | ||
aggregator: Option[T => Unit] = None, | ||
timeout: () => Duration = () => Duration.Zero, | ||
error: Option[Iterable.Error[T]] = None | ||
)(implicit ec: ExecutionContext): Future[T] = { | ||
def executor(previousResponse: Option[T] = None): Future[T] = { | ||
execute(previousResponse).flatMap { response => | ||
// Call aggregator if defined | ||
aggregator.foreach(agg => agg(response)) | ||
|
||
// Validate the response | ||
if (validate(response)) { | ||
Future.successful(response) | ||
} else { | ||
// Check for error validation | ||
error match { | ||
case Some(err) if err.validate(response) => | ||
err.message match { | ||
case Some(errMsg) => Future.failed(new Exception(errMsg(response))) | ||
case None => Future.failed(new Exception("An error occurred")) | ||
} | ||
case _ => | ||
// Sleep for timeout duration, then retry | ||
blocking(Thread.sleep(timeout().toMillis)) | ||
executor(Some(response)) | ||
} | ||
} | ||
} | ||
} | ||
|
||
executor() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters