-
Notifications
You must be signed in to change notification settings - Fork 640
/
Copy pathCustomFieldsCtrl.scala
56 lines (50 loc) · 2.11 KB
/
CustomFieldsCtrl.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package controllers
import scala.concurrent.{ExecutionContext, Future}
import play.api.http.Status
import play.api.libs.json.{JsNumber, JsObject, Json}
import play.api.mvc.{AbstractController, Action, AnyContent, ControllerComponents}
import akka.stream.Materializer
import akka.stream.scaladsl.Sink
import com.sksamuel.elastic4s.http.ElasticDsl.{search, termsAggregation}
import javax.inject.{Inject, Singleton}
import models.Roles
import org.elastic4play.NotFoundError
import org.elastic4play.controllers.Authenticated
import org.elastic4play.database.DBFind
import org.elastic4play.services.DBLists
import org.elastic4play.services.QueryDSL._
@Singleton
class CustomFieldsCtrl @Inject()(
authenticated: Authenticated,
dbfind: DBFind,
dblists: DBLists,
components: ControllerComponents,
implicit val ec: ExecutionContext,
implicit val mat: Materializer
) extends AbstractController(components)
with Status {
def useCount(customField: String): Action[AnyContent] =
authenticated(Roles.read)
.async {
dblists("custom_fields")
.getItems[JsObject]
._1
.collect {
case (_, value) if (value \ "reference").asOpt[String].contains(customField) ⇒ (value \ "type").as[String]
}
.runWith(Sink.head)
.recoverWith { case _ ⇒ Future.failed(NotFoundError(s"CustomField $customField not found")) }
.flatMap { customFieldType ⇒
val filter = and("relations" in ("case", "alert", "caseTemplate"), contains(s"customFields.$customField.$customFieldType"))
dbfind(
indexName ⇒ search(indexName).query(filter.query).aggregations(termsAggregation("t").field("relations"))
).map { searchResponse ⇒
val buckets = searchResponse.aggregations.terms("t").buckets
val total = buckets.map(_.docCount).sum
val result = buckets.map(b ⇒ b.key → JsNumber(b.docCount)) :+ ("total" → JsNumber(total))
Ok(JsObject(result))
}
.recover { case _ ⇒ Ok(Json.obj("total" → 0)) }
}
}
}