问题
I can not come up with solution for Patch semantic:
- if json has no property, I need skip modification
- if json property has
null, I need to remove this property (for not required properties) - 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