【问题标题】:Implementing Google PATCH semantic with Playframework 2.4 Json transformers使用 Playframework 2.4 Json 转换器实现 Google PATCH 语义
【发布时间】:2016-02-29 17:49:43
【问题描述】:

我想不出补丁语义的解决方案:

  1. 如果json没有属性,我需要跳过修改
  2. 如果json属性有null,我需要删除这个属性(对于不需要的属性)
  3. 在其他情况下我需要设置值

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

例如,我需要使用 必需属性“summary” 存储 json。所以:

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

必须转换为:

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

这个json

{"description": null}

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

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

为了这个

{"summary": null}

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

【问题讨论】:

    标签: json playframework playframework-2.0 transform


    【解决方案1】:

    我的解决办法是

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-05
      • 1970-01-01
      相关资源
      最近更新 更多