@@ -3,30 +3,60 @@ package services
3
3
import com .google .inject .Inject
4
4
import models .Person
5
5
import play .api .http .Status
6
- import play .api .libs .json .Format
7
- import play .api .libs .ws .WSClient
6
+ import play .api .libs .json .Json
7
+ import play .api .libs .ws .{ WSAuthScheme , WSClient }
8
8
import play .api .{Configuration , Logging }
9
9
10
+ import java .time .Instant
10
11
import scala .concurrent .{ExecutionContext , Future }
11
12
12
13
class PeopleService @ Inject ()(configuration : Configuration ,
13
14
ws : WSClient )(implicit ec : ExecutionContext ) extends Logging {
14
15
15
- private val baseUrl : String = configuration.get[String ](" people.baseUrl" )
16
- private val apiKey : String = configuration.get[String ](" people.apiKey" )
16
+ private val query =
17
+ """
18
+ |{
19
+ | people(employeeStatuses: ACTIVE) {
20
+ | emailAddress
21
+ | }
22
+ |}
23
+ |""" .stripMargin
24
+
25
+ private val baseUrl : String = configuration.get[String ](" lunagraph.baseUrl" )
26
+
27
+ private val clientId : String = configuration.get[String ](" lunagraph.client.id" )
28
+ private val clientSecret : String = configuration.get[String ](" lunagraph.client.secret" )
29
+ private val clientIssuer : String = configuration.get[String ](" lunagraph.client.issuer" )
30
+
31
+ def getPersons : Future [Either [String , Seq [Person ]]] = for {
32
+ token <- getToken()
33
+ wsRes <- ws.url(s " ${baseUrl}/graphql " )
34
+ .withHttpHeaders(" Authorization" -> s " Bearer ${token}" )
35
+ .post(Json .toJsObject(Map (" query" -> query)))
36
+ res = wsRes.status match {
37
+ case Status .OK =>
38
+ val jsonResult = Json .parse(wsRes.body)
39
+ Right ((jsonResult \ " data" \ " people" ).get.as[Seq [Person ]])
40
+ case _ => logger.error(wsRes.body)
41
+ Left (wsRes.body)
42
+ }
43
+ } yield res
17
44
18
- def getPersons : Future [Either [String , Seq [Person ]]] = {
19
- withAuth[Seq [Person ]](s " $baseUrl/api/people " )
20
- }
21
45
22
- private def withAuth [A ](url : String )(implicit fjs : Format [A ]): Future [Either [String , A ]] = {
23
- ws.url(url).addQueryStringParameters(" apiKey" -> apiKey).get().map { response =>
24
- response.status match {
25
- case Status .OK => Right (response.json.as[A ])
46
+ private def getToken (): Future [Either [String , String ]] = {
47
+ for {
48
+ clientResponse <- ws.url(s " ${clientIssuer}/protocol/openid-connect/token " )
49
+ .withAuth(clientId, clientSecret, WSAuthScheme .BASIC )
50
+ .post(Map (" grant_type" -> Seq (" client_credentials" )))
51
+ parsedResponse = clientResponse.status match {
52
+ case Status .OK =>
53
+ val jsonResponse = Json .parse(clientResponse.body)
54
+ val token = (jsonResponse \ " access_token" ).get.as[String ]
55
+ Right (token)
26
56
case _ =>
27
- logger.error(response .body)
28
- Left (response .body)
57
+ logger.error(clientResponse .body)
58
+ Left (clientResponse .body)
29
59
}
30
- }
60
+ } yield parsedResponse
31
61
}
32
62
}
0 commit comments