Skip to content

Commit

Permalink
Create unified json format for ObjectId (#6413)
Browse files Browse the repository at this point in the history
* Create unified json format for ObjectId

* remove unused imports

Co-authored-by: leowe <[email protected]>
Co-authored-by: Norman Rzepka <[email protected]>
  • Loading branch information
3 people authored Aug 29, 2022
1 parent fa787c1 commit cc5b62c
Show file tree
Hide file tree
Showing 9 changed files with 49 additions and 39 deletions.
2 changes: 1 addition & 1 deletion app/controllers/ScriptController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class ScriptController @Inject()(scriptDAO: ScriptDAO,
private val scriptPublicReads =
((__ \ 'name).read[String](minLength[String](2) or maxLength[String](50)) and
(__ \ 'gist).read[String] and
(__ \ 'owner).read[String](ObjectId.stringObjectIdReads("owner")))(Script.fromForm _)
(__ \ 'owner).read[ObjectId])(Script.fromForm _)

def create: Action[JsValue] = sil.SecuredAction.async(parse.json) { implicit request =>
withJsonBodyUsing(scriptPublicReads) { script =>
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/TaskTypeController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class TaskTypeController @Inject()(taskTypeDAO: TaskTypeDAO,
private val taskTypePublicReads =
((__ \ 'summary).read[String](minLength[String](2) or maxLength[String](50)) and
(__ \ 'description).read[String] and
(__ \ 'teamId).read[String](ObjectId.stringObjectIdReads("teamId")) and
(__ \ 'teamId).read[ObjectId] and
(__ \ 'settings).read[AnnotationSettings] and
(__ \ 'recommendedConfiguration).readNullable[JsValue] and
(__ \ 'tracingType).read[TracingType.Value])(taskTypeService.fromForm _)
Expand Down
8 changes: 2 additions & 6 deletions app/models/mesh/Mesh.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import com.scalableminds.util.accesscontext.DBAccessContext
import com.scalableminds.util.geometry.Vec3Int
import com.scalableminds.util.tools.Fox
import com.scalableminds.webknossos.schema.Tables._

import javax.inject.Inject
import play.api.libs.functional.syntax._
import play.api.libs.json.Json._
import play.api.libs.json._
import slick.jdbc.PostgresProfile.api._
Expand All @@ -30,11 +30,7 @@ case class MeshInfoParameters(
position: Vec3Int,
)
object MeshInfoParameters {
implicit val meshInfoParametersReads: Reads[MeshInfoParameters] =
((__ \ "annotationId").read[String](ObjectId.stringObjectIdReads("teamId")) and
(__ \ "description").read[String] and
(__ \ "position").read[Vec3Int])((annotationId, description, position) =>
MeshInfoParameters(ObjectId(annotationId), description, position))
implicit val jsonFormat: OFormat[MeshInfoParameters] = Json.format[MeshInfoParameters]
}

class MeshService @Inject()()(implicit ec: ExecutionContext) {
Expand Down
6 changes: 3 additions & 3 deletions app/models/project/Project.scala
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,14 @@ object Project {
// format: off
val projectPublicReads: Reads[Project] =
((__ \ 'name).read[String](Reads.minLength[String](3) keepAnd validateProjectName) and
(__ \ 'team).read[String](ObjectId.stringObjectIdReads("team")) and
(__ \ 'team).read[ObjectId] and
(__ \ 'priority).read[Int] and
(__ \ 'paused).readNullable[Boolean] and
(__ \ 'expectedTime).readNullable[Long] and
(__ \ 'owner).read[String](ObjectId.stringObjectIdReads("owner")) and
(__ \ 'owner).read[ObjectId] and
(__ \ 'isBlacklistedFromReport).read[Boolean]) (
(name, team, priority, paused, expectedTime, owner, isBlacklistedFromReport) =>
Project(ObjectId.generate, ObjectId(team), ObjectId(owner), name, priority, paused getOrElse false, expectedTime, isBlacklistedFromReport))
Project(ObjectId.generate, team, owner, name, priority, paused getOrElse false, expectedTime, isBlacklistedFromReport))
// format: on

}
Expand Down
4 changes: 2 additions & 2 deletions app/models/task/Script.scala
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ class ScriptService @Inject()(userDAO: UserDAO, userService: UserService) {
}

object Script {
def fromForm(name: String, gist: String, _owner: String): Script =
Script(ObjectId.generate, ObjectId(_owner), name, gist)
def fromForm(name: String, gist: String, _owner: ObjectId): Script =
Script(ObjectId.generate, _owner, name, gist)
}

class ScriptDAO @Inject()(sqlClient: SQLClient)(implicit ec: ExecutionContext)
Expand Down
4 changes: 2 additions & 2 deletions app/models/task/TaskType.scala
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ class TaskTypeService @Inject()(teamDAO: TeamDAO, taskTypeDAO: TaskTypeDAO)(impl
def fromForm(
summary: String,
description: String,
team: String,
team: ObjectId,
settings: AnnotationSettings,
recommendedConfiguration: Option[JsValue],
tracingType: TracingType
): TaskType =
TaskType(ObjectId.generate, ObjectId(team), summary, description, settings, recommendedConfiguration, tracingType)
TaskType(ObjectId.generate, team, summary, description, settings, recommendedConfiguration, tracingType)

def publicWrites(taskType: TaskType): Fox[JsObject] =
for {
Expand Down
6 changes: 3 additions & 3 deletions app/models/team/TeamMembership.scala
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ class TeamMembershipService @Inject()(teamDAO: TeamDAO) {
team <- teamDAO.findOne(teamMembership.teamId)
} yield {
Json.obj(
"id" -> teamMembership.teamId.toString,
"id" -> teamMembership.teamId,
"name" -> team.name,
"isTeamManager" -> teamMembership.isTeamManager
)
}

def publicReads(): Reads[TeamMembership] =
((__ \ "id").read[String](ObjectId.stringObjectIdReads("id")) and
(__ \ "isTeamManager").read[Boolean])((id, isTeamManager) => TeamMembership(ObjectId(id), isTeamManager))
((__ \ "id").read[ObjectId] and
(__ \ "isTeamManager").read[Boolean])((id, isTeamManager) => TeamMembership(id, isTeamManager))
}
33 changes: 33 additions & 0 deletions app/utils/ObjectId.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package utils

import com.scalableminds.util.tools.{Fox, FoxImplicits}
import play.api.libs.json._
import reactivemongo.bson.BSONObjectID

import scala.concurrent.ExecutionContext

case class ObjectId(id: String) {
override def toString: String = id
}

object ObjectId extends FoxImplicits {
def generate: ObjectId = fromBsonId(BSONObjectID.generate)
def fromString(input: String)(implicit ec: ExecutionContext): Fox[ObjectId] =
fromStringSync(input).toFox ?~> s"The passed resource id ‘$input’ is invalid"
private def fromBsonId(bson: BSONObjectID) = ObjectId(bson.stringify)
private def fromStringSync(input: String) = BSONObjectID.parse(input).map(fromBsonId).toOption
def dummyId: ObjectId = ObjectId("dummyObjectId")

implicit object ObjectIdFormat extends Format[ObjectId] {
override def reads(json: JsValue): JsResult[ObjectId] =
json.validate[String].flatMap { idString =>
val parsedOpt = fromStringSync(idString)
parsedOpt match {
case Some(parsed) => JsSuccess(parsed)
case None => JsError(f"bsonid.invalid: $idString")
}
}

override def writes(o: ObjectId): JsValue = JsString(o.id)
}
}
23 changes: 2 additions & 21 deletions app/utils/SQLHelpers.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,17 @@ package utils
import com.scalableminds.util.accesscontext.DBAccessContext
import com.scalableminds.util.tools.{Fox, FoxImplicits}
import com.typesafe.scalalogging.LazyLogging
import javax.inject.Inject
import models.user.User
import net.liftweb.common.Full
import oxalis.security.{SharingTokenContainer, UserSharingTokenContainer}
import oxalis.telemetry.SlackNotificationService
import play.api.Configuration
import play.api.libs.json.{Json, JsonValidationError, OFormat, Reads}
import reactivemongo.bson.BSONObjectID
import slick.dbio.DBIOAction
import slick.jdbc.PostgresProfile.api._
import slick.jdbc.{PositionedParameters, PostgresProfile, SetParameter}
import slick.lifted.{AbstractTable, Rep, TableQuery}

import javax.inject.Inject
import scala.annotation.nowarn
import scala.concurrent.ExecutionContext
import scala.util.{Failure, Success, Try}
Expand All @@ -25,26 +23,9 @@ class SQLClient @Inject()(configuration: Configuration, slackNotificationService
def getSlackNotificationService: SlackNotificationService = slackNotificationService
}

case class ObjectId(id: String) {
override def toString: String = id
}

object ObjectId extends FoxImplicits {
implicit val jsonFormat: OFormat[ObjectId] = Json.format[ObjectId]
def generate: ObjectId = fromBsonId(BSONObjectID.generate)
def fromString(input: String)(implicit ec: ExecutionContext): Fox[ObjectId] =
fromStringSync(input).toFox ?~> s"The passed resource id ‘$input’ is invalid"
private def fromBsonId(bson: BSONObjectID) = ObjectId(bson.stringify)
private def fromStringSync(input: String) = BSONObjectID.parse(input).map(fromBsonId).toOption
def dummyId: ObjectId = ObjectId("dummyObjectId")

def stringObjectIdReads(key: String): Reads[String] =
Reads.filter[String](JsonValidationError("bsonid.invalid", key))(fromStringSync(_).isDefined)
}

trait SQLTypeImplicits {
implicit object SetObjectId extends SetParameter[ObjectId] {
def apply(v: ObjectId, pp: PositionedParameters) { pp.setString(v.id) }
def apply(v: ObjectId, pp: PositionedParameters): Unit = pp.setString(v.id)
}
}

Expand Down

0 comments on commit cc5b62c

Please sign in to comment.