-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel_patchrequest.go
More file actions
50 lines (42 loc) · 1.28 KB
/
model_patchrequest.go
File metadata and controls
50 lines (42 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package jsonpatch
import (
"encoding/json"
"errors"
"fmt"
)
const (
PatchOperationAdd = "add"
PatchOperationRemove = "remove"
PatchOperationReplace = "replace"
)
type PatchOperation string
type PatchRequest[T any] struct {
Operation PatchOperation `json:"op" validate:"required,oneof=remove replace"` // TODO implements add
Path string `json:"path" validate:"required,jsonpath,ne=$"`
Value any `json:"value"`
}
// Apply TODO
func (pr *PatchRequest[T]) Apply(initialResource *T, emptyResource *T) (*T, error) {
switch pr.Operation {
case PatchOperationReplace:
return pr.replace(initialResource, emptyResource)
case PatchOperationRemove:
return pr.remove(initialResource, emptyResource)
case PatchOperationAdd:
//TODO make the implementation
fallthrough // fallthrough for now
default:
return nil, errors.New("operation not implemented")
}
}
func (pr *PatchRequest[T]) remarshal(resourceAsMap interface{}, emptyResource *T) (*T, error) {
newBytes, err := json.Marshal(resourceAsMap)
if err != nil {
return nil, fmt.Errorf("match fail to marshal input resource %s", err.Error())
}
err = json.Unmarshal(newBytes, &emptyResource)
if err != nil {
return nil, fmt.Errorf("match fail to unmarshal %s", err.Error())
}
return emptyResource, nil
}