2022-03-31 18:34:52 +02:00
|
|
|
package json
|
2019-07-05 11:24:18 -07:00
|
|
|
|
2022-07-10 20:56:31 -07:00
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2019-08-13 11:32:12 -07:00
|
|
|
// JoinPatches joins array of serialized JSON patches to the single JSONPatch array
|
2022-07-10 20:56:31 -07:00
|
|
|
// It accepts patch operations and patches (arrays of patch operations) and returns
|
|
|
|
// a single combined patch.
|
2022-04-01 07:26:47 +02:00
|
|
|
func JoinPatches(patches ...[]byte) []byte {
|
2019-08-13 11:32:12 -07:00
|
|
|
if len(patches) == 0 {
|
2022-07-10 20:56:31 -07:00
|
|
|
return nil
|
2019-08-13 11:32:12 -07:00
|
|
|
}
|
2022-07-10 20:56:31 -07:00
|
|
|
|
|
|
|
var patchOperations []string
|
|
|
|
for _, patch := range patches {
|
|
|
|
str := strings.TrimSpace(string(patch))
|
|
|
|
if len(str) == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if strings.HasPrefix(str, "[") {
|
|
|
|
str = strings.TrimPrefix(str, "[")
|
|
|
|
str = strings.TrimSuffix(str, "]")
|
|
|
|
str = strings.TrimSpace(str)
|
2019-08-13 11:32:12 -07:00
|
|
|
}
|
2022-07-10 20:56:31 -07:00
|
|
|
|
|
|
|
patchOperations = append(patchOperations, str)
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(patchOperations) == 0 {
|
|
|
|
return nil
|
2019-08-13 11:32:12 -07:00
|
|
|
}
|
2022-07-10 20:56:31 -07:00
|
|
|
|
|
|
|
result := "[" + strings.Join(patchOperations, ", ") + "]"
|
|
|
|
return []byte(result)
|
2019-08-13 11:32:12 -07:00
|
|
|
}
|