Skip to content

Commit 2a6f6cd

Browse files
Merge pull request #58 from hmrc/APID-497
APID-497 - Upgrade to hmrc-mongo repo
2 parents 62fb7c3 + a037f19 commit 2a6f6cd

File tree

18 files changed

+190
-202
lines changed

18 files changed

+190
-202
lines changed

app/uk/gov/hmrc/apiscope/controllers/ScopeController.scala

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import uk.gov.hmrc.apiscope.models.ErrorCode._
2525
import uk.gov.hmrc.apiscope.models.{Scope, ScopeData}
2626
import uk.gov.hmrc.apiscope.services.ScopeService
2727
import uk.gov.hmrc.play.bootstrap.backend.controller.BackendController
28+
import uk.gov.hmrc.apiscope.models.ResponseFormatters._
2829

2930
@Singleton
3031
class ScopeController @Inject()(scopeService: ScopeService, cc: ControllerComponents, playBodyParsers: PlayBodyParsers)(implicit val ec: ExecutionContext)

app/uk/gov/hmrc/apiscope/models/ConfidenceLevel.scala

Lines changed: 9 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -16,38 +16,17 @@
1616

1717
package uk.gov.hmrc.apiscope.models
1818

19-
import play.api.libs.json._
19+
import enumeratum.values.{IntEnum, IntEnumEntry, IntPlayJsonValueEnum}
2020

21-
object ConfidenceLevel extends Enumeration {
22-
type ConfidenceLevel = Value
21+
import scala.collection.immutable
2322

24-
val L50, L200, L250, L500 = Value
23+
sealed abstract class ConfidenceLevel(val value: Int) extends IntEnumEntry
2524

26-
private val fromInt = Map(
27-
50 -> L50,
28-
200 -> L200,
29-
250 -> L250,
30-
500 -> L500
31-
)
25+
object ConfidenceLevel extends IntEnum[ConfidenceLevel] with IntPlayJsonValueEnum[ConfidenceLevel] {
26+
val values: immutable.IndexedSeq[ConfidenceLevel] = findValues
3227

33-
private val loadFromInt = Map(
34-
50 -> L50,
35-
100 -> L200, // TODO - replace this value in the database once we know this allows Agent IV etc.
36-
200 -> L200,
37-
250 -> L250,
38-
300 -> L200, // TODO - replace this value in the database once we know this allows Agent IV etc.
39-
500 -> L500
40-
)
41-
42-
private val toInt = fromInt.map(_.swap)
43-
44-
val errorMessage = s"confidence level must be one of: ${fromInt.keys.toSeq.sorted.mkString(", ")}"
45-
46-
implicit val reads = Reads[ConfidenceLevel] { json =>
47-
json.asOpt[Int].flatMap(loadFromInt.get)
48-
.map(JsSuccess(_))
49-
.getOrElse(JsError(errorMessage))
50-
}
51-
52-
implicit val writes = Writes[ConfidenceLevel] { LoC => JsNumber(toInt(LoC)) }
28+
case object L50 extends ConfidenceLevel(50)
29+
case object L200 extends ConfidenceLevel(200)
30+
case object L250 extends ConfidenceLevel(250)
31+
case object L500 extends ConfidenceLevel(500)
5332
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
* Copyright 2022 HM Revenue & Customs
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package uk.gov.hmrc.apiscope.models
18+
19+
import play.api.libs.json.Json
20+
21+
object ResponseFormatters {
22+
implicit val scopeFormat = Json.format[Scope]
23+
24+
}

app/uk/gov/hmrc/apiscope/models/Scope.scala

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,8 @@
1616

1717
package uk.gov.hmrc.apiscope.models
1818

19-
import play.api.libs.json.Json
20-
21-
import uk.gov.hmrc.apiscope.models.ConfidenceLevel.ConfidenceLevel
2219

2320
case class Scope(key: String, name: String, description: String, confidenceLevel: Option[ConfidenceLevel] = None)
2421

25-
object Scope {
26-
implicit val formats = Json.format[Scope]
27-
}
22+
23+

app/uk/gov/hmrc/apiscope/models/ScopeRequest.scala

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ package uk.gov.hmrc.apiscope.models
1818

1919
import play.api.libs.json.Json
2020

21-
import uk.gov.hmrc.apiscope.models.ConfidenceLevel.ConfidenceLevel
2221

2322
case class ScopeData(key: String, name: String, description: String, confidenceLevel: Option[ConfidenceLevel] = None) {
2423
require(key.trim.nonEmpty, s"scope key is required")

app/uk/gov/hmrc/apiscope/repository/ScopeRepository.scala

Lines changed: 61 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -16,62 +16,84 @@
1616

1717
package uk.gov.hmrc.apiscope.repository
1818

19-
import javax.inject.{Inject, Singleton}
19+
import org.bson.codecs.configuration.CodecRegistries.{fromCodecs, fromRegistries}
20+
import org.mongodb.scala.model.Filters.equal
21+
import org.mongodb.scala.model.Indexes.ascending
22+
import org.mongodb.scala.model.Updates.{combine, set}
23+
import org.mongodb.scala.model.{FindOneAndUpdateOptions, IndexModel, IndexOptions, ReturnDocument}
24+
import org.mongodb.scala.{MongoClient, MongoCollection}
25+
import play.api.Logger
26+
import play.api.libs.json.{Json, OFormat}
27+
import uk.gov.hmrc.apiscope.models.Scope
28+
import uk.gov.hmrc.mongo.MongoComponent
29+
import uk.gov.hmrc.mongo.play.json.{Codecs, CollectionFactory, PlayMongoRepository}
2030

31+
import javax.inject.{Inject, Singleton}
2132
import scala.collection.Seq
2233
import scala.concurrent.{ExecutionContext, Future}
23-
import reactivemongo.api.Cursor
24-
import reactivemongo.api.indexes.{Index, IndexType}
25-
import reactivemongo.bson.BSONObjectID
26-
import reactivemongo.play.json.ImplicitBSONHandlers._
27-
import play.api.libs.json.{JsObject, Json}
28-
import play.api.libs.json.Json._
29-
import play.modules.reactivemongo.ReactiveMongoComponent
30-
import uk.gov.hmrc.mongo.ReactiveRepository
31-
import uk.gov.hmrc.mongo.json.ReactiveMongoFormats
32-
import uk.gov.hmrc.apiscope.models.Scope
34+
3335

3436
private object ScopeFormats {
35-
implicit val objectIdFormats = ReactiveMongoFormats.objectIdFormats
36-
implicit val scopeFormat = Json.format[Scope]
37+
implicit val scopeFormat:OFormat[Scope] = Json.format[Scope]
3738
}
3839

3940
@Singleton
40-
class ScopeRepository @Inject()(mongo: ReactiveMongoComponent)(implicit val ec: ExecutionContext)
41-
extends ReactiveRepository[Scope, BSONObjectID]("scope", mongo.mongoConnector.db,
42-
ScopeFormats.scopeFormat, ReactiveMongoFormats.objectIdFormats) {
43-
41+
class ScopeRepository @Inject()(mongoComponent: MongoComponent)(implicit val ec: ExecutionContext)
42+
extends PlayMongoRepository[Scope](
43+
mongoComponent = mongoComponent,
44+
collectionName = "scope",
45+
domainFormat = ScopeFormats.scopeFormat,
46+
indexes = Seq(IndexModel(ascending("key"),
47+
IndexOptions()
48+
.name("keyIndex")
49+
.background(true)
50+
.unique(true))),
51+
replaceIndexes = true
52+
) {
53+
private val logger = Logger(this.getClass)
4454

45-
ensureIndex("key", "keyIndex")
55+
override lazy val collection: MongoCollection[Scope] =
56+
CollectionFactory
57+
.collection(mongoComponent.database, collectionName, domainFormat)
58+
.withCodecRegistry(
59+
fromRegistries(
60+
fromCodecs(
61+
Codecs.playFormatCodec(domainFormat)
62+
),
63+
MongoClient.DEFAULT_CODEC_REGISTRY
64+
)
65+
)
4666

4767
def save(scope: Scope) : Future[Scope] = {
48-
collection
49-
.update(false).one(Json.obj("key" -> scope.key), scope, upsert = true)
50-
.map(_ => scope)
51-
}
52-
53-
private def ensureIndex(field: String, indexName: String, isUnique: Boolean = true, isBackground: Boolean = true): Future[Boolean] = {
54-
def createIndex = Index(
55-
key = Seq(field -> IndexType.Ascending),
56-
name = Some(indexName),
57-
unique = isUnique,
58-
background = isBackground
59-
)
60-
61-
collection.indexesManager.ensure(createIndex)
68+
var updateSeq = Seq(
69+
set("key", Codecs.toBson(scope.key)),
70+
set("name", Codecs.toBson(scope.name)),
71+
set("description", Codecs.toBson(scope.description)))
72+
scope.confidenceLevel match {
73+
case Some(value) =>
74+
logger.info(s"confidenceLevel value id ${value} and value enumeration ${value.value}")
75+
updateSeq = updateSeq :+ set("confidenceLevel", Codecs.toBson(value))
76+
case None => Future.successful(None)
77+
}
78+
logger.info(s"updateSeq: $updateSeq")
79+
collection.findOneAndUpdate(equal("key", Codecs.toBson(scope.key)),
80+
update = combine(updateSeq: _*),
81+
options = FindOneAndUpdateOptions().upsert(true).returnDocument(ReturnDocument.AFTER)
82+
).map(_.asInstanceOf[Scope]).head()
6283
}
6384

6485
def fetch(key: String): Future[Option[Scope]] = {
65-
collection.find[JsObject, Scope](Json.obj("key" -> key), None).one[Scope]. map {
66-
case Some(s) => Some(s)
67-
case None =>
68-
logger.info(s"The scope $key doesn't exist")
69-
None
70-
}
86+
collection.find(equal("key", key)).headOption()
87+
.flatMap {
88+
case Some(scope) => Future.successful(Some(scope))
89+
case None =>
90+
logger.info(s"The scope $key doesn't exist")
91+
Future.successful(None)
92+
}
7193
}
7294

7395
def fetchAll(): Future[Seq[Scope]] = {
74-
collection.find[JsObject, Scope](Json.obj(), None).cursor[Scope]().collect[Seq](Int.MaxValue,Cursor.FailOnError[Seq[Scope]]())
96+
collection.find().toFuture()
7597
}
7698

7799
}

app/uk/gov/hmrc/apiscope/services/ScopeJsonFileService.scala

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import uk.gov.hmrc.apiscope.repository.ScopeRepository
2525
import scala.concurrent.{ExecutionContext, Future}
2626
import scala.util.{Failure, Success}
2727
import scala.util.control.NonFatal
28+
import uk.gov.hmrc.apiscope.models.ResponseFormatters._
2829

2930
@Singleton
3031
class ScopeJsonFileService @Inject()(scopeRepository: ScopeRepository,

build.sbt

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,6 @@ import uk.gov.hmrc.DefaultBuildSettings._
77
import uk.gov.hmrc.sbtdistributables.SbtDistributablesPlugin._
88
import bloop.integrations.sbt.BloopDefaults
99

10-
ThisBuild / scalafixDependencies += "com.github.liancheng" %% "organize-imports" % "0.5.0"
11-
12-
inThisBuild(
13-
List(
14-
scalaVersion := "2.12.12",
15-
semanticdbEnabled := true,
16-
semanticdbVersion := scalafixSemanticdb.revision
17-
)
18-
)
19-
2010
lazy val appName = "api-scope"
2111

2212
lazy val playSettings: Seq[Setting[_]] = Seq.empty
@@ -31,9 +21,8 @@ lazy val microservice = Project(appName, file("."))
3121
.settings(
3222
majorVersion := 0,
3323
targetJvm := "jvm-1.8",
34-
scalaVersion := "2.12.12",
24+
scalaVersion := "2.12.15",
3525
libraryDependencies ++= AppDependencies.libraryDependencies,
36-
dependencyOverrides ++= AppDependencies.dependencyOverrides,
3726
retrieveManaged := true
3827
)
3928
.settings(

conf/application.conf

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ play.http.router=prod.Routes
8282
# Play modules
8383
# ~~~~~
8484
play.modules.enabled += "uk.gov.hmrc.play.bootstrap.HttpClientModule"
85-
play.modules.enabled += "play.modules.reactivemongo.ReactiveMongoHmrcModule"
85+
play.modules.enabled += "uk.gov.hmrc.mongo.play.PlayMongoModule"
8686

8787
# Controller
8888
# ~~~~~

integration/uk/gov/hmrc/apiscope/ScopeFeatureSpec.scala

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,8 @@ package uk.gov.hmrc.apiscope
1818

1919
import java.util.concurrent.TimeUnit
2020
import scala.concurrent.Await.result
21-
import scala.concurrent.ExecutionContext.Implicits.global
2221
import scala.concurrent.duration.Duration
23-
2422
import scalaj.http.Http
25-
2623
import play.api.libs.json.{JsValue, Json}
2724

2825
import uk.gov.hmrc.apiscope.repository.ScopeRepository
@@ -96,7 +93,7 @@ class ScopeFeatureSpec extends BaseFeatureSpec {
9693
}
9794

9895
def dropDatabase = {
99-
result(repository.drop, timeout)
96+
repository.collection.drop()
10097
result(repository.ensureIndexes, timeout)
10198
}
10299

0 commit comments

Comments
 (0)