使用Playframework 2.4 Json转换器实现Google PATCH语义 [英] Implementing Google PATCH semantic with Playframework 2.4 Json transformers

查看:122
本文介绍了使用Playframework 2.4 Json转换器实现Google PATCH语义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法提出补丁语义的解决方案:

I can not come up with solution for Patch semantic:

  1. 如果json没有属性,我需要跳过修改
  2. 如果json属性具有null,则需要删除此属性(对于非必需属性)
  3. 在其他情况下,我需要设置值
  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

我需要转换为mongo.db更新命令("$ unset"代表2,"$ set"代表3)

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

例如,我需要使用必填属性"summary" 存储json.所以:

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

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

必须转换为:

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

这个json

{"description": null}

必须转换为(跳过摘要"):

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

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

为此

{"summary": null}

我需要转换错误(无法删除必需的属性)

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

推荐答案

我的解决方案是

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

以及所需的属性

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

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

其他

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

mongo.db变形器:

toMongoPatch = (summaryPatch and descriptionPatch).reduce

这篇关于使用Playframework 2.4 Json转换器实现Google PATCH语义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆