Implementing Google PATCH semantic with Playframework 2.4 Json transformers

只谈情不闲聊 提交于 2019-12-12 02:45:37

问题


I can not come up with solution for Patch semantic:

  1. if json has no property, I need skip modification
  2. if json property has null, I need to remove this property (for not required properties)
  3. in other cases I need to set the value

I need transformation into mongo.db update command ("$unset" for 2, "$set" for 3)

For example I need store json with required property "summary". So:

{"summary": "modified by patch", "description": null}

must be transformed to:

{
  "$set" : {
    "summary": "modified by patch"
  },
  "$unset": {
    "description": ""
  }
}

this json

{"description": null}

must be transformed to ("summary" is skipped):

{
  "$unset" : {
    "description": ""
  }
}

and for this

{"summary": null}

I need transformation error (can't remove required properties)


回答1:


My solution is

def patch(path: JsPath)(r: Reads[JsObject]) = Reads{json =>
  path.asSingleJsResult(json).fold(
    _ => JsSuccess(Json.obj()),
    _ => r.reads(json)
  )
}

and for requiered properties

def requiredError = ValidationError("error.remove.required")

val summaryPatch = patch(__ \ "summary")(
  (__ \ "$set" \ "summary").json.copyFrom( 
    (__ \ "summary").json.pick.filterNot(requiredError)(_ == JsNull)
  )
)

for other

val descriptionPatch = patch(__ \ "description")(
  (__ \ "$set" \ "description").json.copyFrom(
    (__ \ "description").json.pick.filterNot(_ == JsNull) 
  ) orElse 
  (__ \ "$unset" \ "description").json.copyFrom( 
    (__ \ "description").json.pick) 
  )
)

to mongo.db trasformer:

toMongoPatch = (summaryPatch and descriptionPatch).reduce


来源:https://stackoverflow.com/questions/35706086/implementing-google-patch-semantic-with-playframework-2-4-json-transformers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!