How to do PATCH properly in strongly typed languages based on Spring - example

后端 未结 4 1322
甜味超标
甜味超标 2020-12-23 16:10

According to my knowledge:

  • PUT - update object with its whole representation (replace)
  • PATCH - update object with given fiel
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-23 16:48

    What I do in some of the applications is create an OptionalInput class which can distinguish whether a value is set or not:

    class OptionalInput {
    
        private boolean _isSet = false
    
        @Valid
        private T value
    
        void set(T value) {
            this._isSet = true
            this.value = value
        }
    
        T get() {
            return this.value
        }
    
        boolean isSet() {
            return this._isSet
        }
    }
    

    Then in your request class:

    class PatchUserRequest {
    
        @OptionalInputLength(max = 100L)
        final OptionalInput name = new OptionalInput<>()
    
        void setName(String name) {
            this.name.set(name)
        }
    }
    

    The properties can be validated by creating a @OptionalInputLength.

    Usage is:

    void update(@Valid @RequestBody PatchUserRequest request) {
        if (request.name.isSet()) {
            // Do the stuff
        }
    }
    

    NOTE: The code is written in groovy but you get the idea. I've used this approach for a few APIs already and it seems to be doing it's job quite well.

提交回复
热议问题