Skip to content

Commit 11944da

Browse files
committed
fix: a lot of scala stuff
1 parent 0a204d8 commit 11944da

File tree

16 files changed

+61
-49
lines changed

16 files changed

+61
-49
lines changed

clients/algoliasearch-client-scala/src/main/scala/algoliasearch/extension/package.scala

Lines changed: 35 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ package object extension {
2626
/** Converts the restrictions to a URL-encoded string. Only includes fields that are defined (Some).
2727
*/
2828
def toUrlEncoded: String = {
29-
implicit val formats: Formats = DefaultFormats
29+
implicit val formats: Formats = JsonSupport.format
3030

3131
val jValue = Extraction.decompose(restrictions.searchParams)
3232
var baseParams = jValue.extract[Map[String, Any]]
@@ -36,7 +36,7 @@ package object extension {
3636
}
3737

3838
if (restrictions.validUntil.isDefined) {
39-
baseParams += ("validUntil" -> restrictions.validUntil.get.toInt)
39+
baseParams += ("validUntil" -> restrictions.validUntil.get)
4040
}
4141

4242
if (restrictions.restrictIndices.isDefined) {
@@ -73,6 +73,12 @@ package object extension {
7373
* The maximum number of retries. 50 by default. (optional)
7474
* @param requestOptions
7575
* Additional request configuration.
76+
* @return Option[GetApiKeyResponse]
77+
* The response of the operation.
78+
* - for `add` operation, either Some(GetApiKeyResponse) if the key is created or None if the key is not created.
79+
* - for `update` operation, Some(GetApiKeyResponse) with the updated key
80+
* - for `delete` operation, either None if the key is deleted or Some(GetApiKeyResponse) if the key is not deleted.
81+
*
7682
*/
7783
def waitForApiKey(
7884
operation: ApiKeyOperation,
@@ -81,7 +87,7 @@ package object extension {
8187
maxRetries: Int = 50,
8288
delay: Long => Long = DEFAULT_DELAY,
8389
requestOptions: Option[RequestOptions] = None
84-
)(implicit ec: ExecutionContext): Future[Any] = {
90+
)(implicit ec: ExecutionContext): Future[Option[GetApiKeyResponse]] = {
8591
operation match {
8692
case ApiKeyOperation.Add =>
8793
client.waitKeyCreation(key, maxRetries, delay, requestOptions)
@@ -113,10 +119,10 @@ package object extension {
113119
delay: Long => Long = DEFAULT_DELAY,
114120
maxRetries: Int = 50,
115121
requestOptions: Option[RequestOptions] = None
116-
)(implicit ec: ExecutionContext): Future[TaskStatus] = {
122+
)(implicit ec: ExecutionContext): Future[GetTaskResponse] = {
117123
retryUntil(
118-
retry = () => client.getTask(indexName, taskID, requestOptions).map(_.status),
119-
until = (status: TaskStatus) => status == TaskStatus.Published,
124+
retry = () => client.getTask(indexName, taskID, requestOptions),
125+
until = (res: GetTaskResponse) => res.status == TaskStatus.Published,
120126
maxRetries = maxRetries,
121127
delay = delay
122128
)
@@ -130,7 +136,7 @@ package object extension {
130136
maxRetries: Int = 50,
131137
requestOptions: Option[RequestOptions] = None
132138
)(implicit ec: ExecutionContext): Future[TaskStatus] = {
133-
waitForTask(indexName, taskID, delay, maxRetries, requestOptions)
139+
waitForTask(indexName, taskID, delay, maxRetries, requestOptions).map(_.status)
134140
}
135141

136142
/** Wait for an application-level taskID to complete before executing the next line of code.
@@ -147,10 +153,10 @@ package object extension {
147153
delay: Long => Long = DEFAULT_DELAY,
148154
maxRetries: Int = 50,
149155
requestOptions: Option[RequestOptions] = None
150-
)(implicit ec: ExecutionContext): Future[TaskStatus] = {
156+
)(implicit ec: ExecutionContext): Future[GetTaskResponse] = {
151157
retryUntil(
152-
retry = () => client.getAppTask(taskID, requestOptions).map(_.status),
153-
until = (status: TaskStatus) => status == TaskStatus.Published,
158+
retry = () => client.getAppTask(taskID, requestOptions),
159+
until = (res: GetTaskResponse) => res.status == TaskStatus.Published,
154160
maxRetries = maxRetries,
155161
delay = delay
156162
)
@@ -163,7 +169,7 @@ package object extension {
163169
maxRetries: Int = 50,
164170
requestOptions: Option[RequestOptions] = None
165171
)(implicit ec: ExecutionContext): Future[TaskStatus] = {
166-
waitForAppTask(taskID, delay, maxRetries, requestOptions)
172+
waitForAppTask(taskID, delay, maxRetries, requestOptions).map(_.status)
167173
}
168174

169175
/** Wait on an API key update operation.
@@ -183,7 +189,7 @@ package object extension {
183189
maxRetries: Int = 50,
184190
delay: Long => Long = DEFAULT_DELAY,
185191
requestOptions: Option[RequestOptions] = None
186-
)(implicit ec: ExecutionContext): Future[GetApiKeyResponse] = {
192+
)(implicit ec: ExecutionContext): Future[Option[GetApiKeyResponse]] = {
187193
retryUntil(
188194
retry = () => client.getApiKey(key, requestOptions),
189195
until = (res: GetApiKeyResponse) =>
@@ -194,11 +200,12 @@ package object extension {
194200
maxHitsPerQuery = res.maxHitsPerQuery,
195201
maxQueriesPerIPPerHour = res.maxQueriesPerIPPerHour,
196202
queryParameters = res.queryParameters,
197-
referers = res.referers
203+
referers = res.referers,
204+
validity = res.validity
198205
),
199206
maxRetries = maxRetries,
200207
delay = delay
201-
)
208+
).map(Some(_))
202209
}
203210

204211
/** Wait on an API key creation operation.
@@ -215,7 +222,7 @@ package object extension {
215222
maxRetries: Int = 50,
216223
delay: Long => Long = DEFAULT_DELAY,
217224
requestOptions: Option[RequestOptions] = None
218-
)(implicit ec: ExecutionContext): Future[GetApiKeyResponse] = {
225+
)(implicit ec: ExecutionContext): Future[Option[GetApiKeyResponse]] = {
219226
retryUntil(
220227
retry = () =>
221228
client
@@ -225,7 +232,7 @@ package object extension {
225232
until = (res: Option[GetApiKeyResponse]) => res.isDefined,
226233
maxRetries = maxRetries,
227234
delay = delay
228-
).map(_.get)
235+
)
229236
}
230237

231238
/** Wait on a delete API ket operation
@@ -242,25 +249,24 @@ package object extension {
242249
maxRetries: Int = 50,
243250
delay: Long => Long = DEFAULT_DELAY,
244251
requestOptions: Option[RequestOptions] = None
245-
)(implicit ec: ExecutionContext): Future[Boolean] = {
252+
)(implicit ec: ExecutionContext): Future[Option[GetApiKeyResponse]] = {
246253
retryUntil(
247254
retry = () =>
248255
client
249256
.getApiKey(key, requestOptions)
250-
.map(_ => None) // The key still exists, return None
257+
.map(Some(_))
251258
.recover {
252-
case e: AlgoliaApiException if e.httpErrorCode == 404 => Some(true) // The key does not exist, done!
253-
case _ => None // Any other error, still return None
259+
case e: AlgoliaApiException if e.httpErrorCode == 404 => None // The key does not exist, done!
260+
case exc => throw exc // Any other error, rethrow
254261
},
255-
until = (result: Option[Boolean]) =>
262+
until = (result: Option[GetApiKeyResponse]) =>
256263
result match {
257-
case Some(true) => true // Stop retrying when we get Some(true), indicating the key is deleted
258-
case _ => false // Continue retrying otherwise
264+
case None => true // Stop retrying when we get None, indicating the key is deleted
265+
case Some(_) => false // As long as we get a key, keep retrying
259266
},
260267
maxRetries = maxRetries,
261268
delay = delay
262269
)
263-
Future.successful(true)
264270
}
265271

266272
/** Helper: Chunks the given `objects` list in subset of 1000 elements max to make it fit in `batch` requests.
@@ -365,7 +371,7 @@ package object extension {
365371
)(implicit ec: ExecutionContext): Future[Seq[BatchResponse]] = {
366372
chunkedBatch(
367373
indexName,
368-
objectIDs.map(id => new { val objectID: String = id }),
374+
objectIDs.map(id => Map("objectID" -> id)),
369375
Action.DeleteObject,
370376
waitForTasks,
371377
batchSize,
@@ -499,14 +505,10 @@ package object extension {
499505
* A future containing a boolean indicating if the index exists.
500506
*/
501507
def indexExists(indexName: String)(implicit ec: ExecutionContext): Future[Boolean] = {
502-
try {
503-
client.getSettings(indexName)
504-
} catch {
505-
case apiError: AlgoliaApiException if apiError.httpErrorCode == 404 => Future.successful(false)
506-
case e: Throwable => throw e
508+
client.getSettings(indexName).map(_ => true).recover {
509+
case apiError: AlgoliaApiException if apiError.httpErrorCode == 404 => false
510+
case e => throw e
507511
}
508-
509-
Future.successful(true)
510512
}
511513

512514
/** Browse objects in an index.
@@ -638,8 +640,7 @@ package object extension {
638640
val secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), algorithm)
639641
val mac = Mac.getInstance(algorithm)
640642
mac.init(secretKey)
641-
val hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8))
642-
java.util.Base64.getEncoder.encodeToString(hash)
643+
mac.doFinal(data.getBytes(StandardCharsets.UTF_8)).map("%02x".format(_)).mkString
643644
}
644645

645646
/** Generate a secured API key

clients/algoliasearch-client-scala/src/main/scala/algoliasearch/internal/util/package.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ package object util {
3333
throw new UnsupportedOperationException(
3434
"Date must come as string (already serialized)"
3535
)
36-
case c: Iterable[_] => c.map(_.toString).mkString(",")
36+
case c: Iterable[?] => c.map(_.toString).mkString(",")
3737
case _ => value.toString
3838
}
3939
}

clients/algoliasearch-client-swift/Sources/Search/Extra/SecuredApiKeyRestrictionExtension.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ public extension SecuredApiKeyRestrictions {
2323
queryDictionary["filters"] = filters
2424
}
2525
if let validUntil {
26-
queryDictionary["validUntil"] = Int(validUntil)
26+
queryDictionary["validUntil"] = validUntil
2727
}
2828
if let restrictIndices {
2929
queryDictionary["restrictIndices"] = restrictIndices

templates/scala/guides/ingestion/pushSetup.mustache

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import org.json4s.jvalue2extractable
1212
object PushSetup {
1313
def main(args: Array[String]): Unit = {
1414
implicit val ec: ExecutionContextExecutor = scala.concurrent.ExecutionContext.global
15-
implicit val formats: org.json4s.Formats = org.json4s.DefaultFormats
15+
implicit val formats: org.json4s.Formats = JsonSupport.format
1616
1717
val result = Source.fromFile("records.json").getLines().mkString
1818
val records = JsonMethods.parse(result).extract[Seq[algoliasearch.ingestion.PushTaskRecords]]

templates/scala/guides/search/saveObjectsChunks.mustache

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import algoliasearch.config.RequestOptions
1313

1414

1515
def saveObjectsChunks(): Future[Unit] = {
16-
implicit val formats: org.json4s.Formats = org.json4s.DefaultFormats
16+
implicit val formats: org.json4s.Formats = JsonSupport.format
1717
1818
val path = "/tmp/records.json"
1919
val result = Using(Source.fromFile(path))(_.mkString).getOrElse {

templates/scala/guides/search/saveObjectsModified.mustache

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import org.json4s.jvalue2extractable
1111
{{> snippets/import}}
1212

1313
def saveObjectsModified(): Future[Unit] = {
14-
implicit val formats: org.json4s.Formats = org.json4s.DefaultFormats
14+
implicit val formats: org.json4s.Formats = JsonSupport.format
1515
1616
{{> snippets/init}}
1717

templates/scala/guides/search/saveObjectsMovies.mustache

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import org.json4s.jvalue2extractable
1111
object Main {
1212
def main(args: Array[String]): Unit = {
1313
implicit val ec: ExecutionContextExecutor = scala.concurrent.ExecutionContext.global
14-
implicit val formats: org.json4s.Formats = org.json4s.DefaultFormats
14+
implicit val formats: org.json4s.Formats = JsonSupport.format
1515
1616
// Fetch sample dataset
1717
val url = "https://dashboard.algolia.com/api/1/sample_datasets?type=movie"

templates/scala/jsonSupport.mustache

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,13 @@ package {{modelPackage}}
44
import org.json4s._
55

66
object JsonSupport {
7-
private def enumSerializers: Seq[Serializer[_]] = Seq[Serializer[_]](){{#models}}{{#model}}{{#isEnum}} :+
7+
private def enumSerializers: Seq[Serializer[?]] = Seq[Serializer[?]](){{#models}}{{#model}}{{#isEnum}} :+
88
new {{classname}}Serializer(){{/isEnum}}{{/model}}{{/models}}
99

10-
private def oneOfsSerializers: Seq[Serializer[_]] = Seq[Serializer[_]](){{#models}}{{#model}}{{#vendorExtensions.x-is-one-of}}:+
10+
private def oneOfsSerializers: Seq[Serializer[?]] = Seq[Serializer[?]](){{#models}}{{#model}}{{#vendorExtensions.x-is-one-of}}:+
1111
{{classname}}Serializer{{/vendorExtensions.x-is-one-of}}{{/model}}{{/models}}
1212

13-
private def classMapSerializers: Seq[Serializer[_]] = Seq[Serializer[_]](){{#models}}{{#model}}{{#additionalProperties.isAnyType}}:+
13+
private def classMapSerializers: Seq[Serializer[?]] = Seq[Serializer[?]](){{#models}}{{#model}}{{#additionalProperties.isAnyType}}:+
1414
new {{classname}}Serializer(){{/additionalProperties.isAnyType}}{{/model}}{{/models}}
1515

1616
implicit val format: Formats = DefaultFormats ++ enumSerializers ++ oneOfsSerializers ++ classMapSerializers

templates/scala/snippets/method.mustache

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import scala.concurrent.{Await, ExecutionContextExecutor}
1414

1515
class Snippet{{client}} {
1616
implicit val ec: ExecutionContextExecutor = scala.concurrent.ExecutionContext.global
17-
implicit val formats: Formats = org.json4s.DefaultFormats
17+
implicit val formats: Formats = JsonSupport.format
1818
1919
{{#blocksRequests}}
2020
{{#snippets}}

templates/scala/tests/client/client.mustache

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import scala.concurrent.{Await, ExecutionContextExecutor}
2121

2222
class {{clientPrefix}}Test extends AnyFunSuite {
2323
implicit val ec: ExecutionContextExecutor = scala.concurrent.ExecutionContext.global
24-
implicit val formats: Formats = org.json4s.DefaultFormats
24+
implicit val formats: Formats = JsonSupport.format
2525
2626
def testClient(appId: String = "appId", apiKey: String = "apiKey"{{#hasRegionalHost}}, region: String = {{#fallbackToAliasHost}}null{{/fallbackToAliasHost}}{{^fallbackToAliasHost}}"{{defaultRegion}}"{{/fallbackToAliasHost}}{{/hasRegionalHost}}): ({{client}}, EchoInterceptor) = {
2727
val echo = EchoInterceptor()
@@ -75,10 +75,18 @@ class {{clientPrefix}}Test extends AnyFunSuite {
7575
{{/testHost}}
7676
{{#testResponse}}
7777
{{^match.isPrimitive}}
78-
assert(write(res) == "{{#lambda.escapeQuotes}}{{{match.value}}}{{/lambda.escapeQuotes}}")
78+
assert(parse(write(res)) == parse("{{#lambda.escapeQuotes}}{{{match.value}}}{{/lambda.escapeQuotes}}"))
7979
{{/match.isPrimitive}}
8080
{{#match.isPrimitive}}
81+
{{#isHelper}}{{#match.isNull}}
82+
assert(res.isEmpty)
83+
{{/match.isNull}}
84+
{{^match.isNull}}
8185
assert(res == {{#match}}{{> tests/param_value}}{{/match}})
86+
{{/match.isNull}}{{/isHelper}}
87+
{{^isHelper}}
88+
assert(res == {{#match}}{{> tests/param_value}}{{/match}})
89+
{{/isHelper}}
8290
{{/match.isPrimitive}}
8391
{{/testResponse}}
8492
{{#shouldScope}}

0 commit comments

Comments
 (0)