Skip to content

Commit

Permalink
Merge pull request #7 from up9inc/extensions-key-sorted
Browse files Browse the repository at this point in the history
Fix operation extensions are not sorted regularly
  • Loading branch information
chanced committed Feb 24, 2022
2 parents 6172e11 + 0afd043 commit a8e1514
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
13 changes: 11 additions & 2 deletions extension.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package openapi

import (
"encoding/json"
"sort"
"strings"

"github.com/tidwall/sjson"
Expand Down Expand Up @@ -134,8 +135,16 @@ func marshalExtendedJSON(dst extended) ([]byte, error) {

func marshalExtendedJSONInto(data []byte, obj extended) ([]byte, error) {
var err error
for k, v := range obj.exts() {
data, err = sjson.SetBytes(data, k, v)

exts := obj.exts()
keys := make([]string, 0, len(exts))
for k := range exts {
keys = append(keys, k)
}
sort.Strings(keys)

for _, k := range keys {
data, err = sjson.SetBytes(data, k, exts[k])
if err != nil {
return data, err
}
Expand Down
16 changes: 16 additions & 0 deletions operation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package openapi_test
import (
"encoding/json"
"fmt"
"strconv"
"testing"

"github.com/chanced/cmpjson"
Expand Down Expand Up @@ -104,3 +105,18 @@ func TestOperation(t *testing.T) {

}
}

func TestExtensionSorting(t *testing.T) {
assert := require.New(t)
exp := `{"x-key1":1,"x-key2":2}`
for n := 0; n < 100; n++ {
op := new(openapi.Operation)
op.Extensions = make(openapi.Extensions)
op.Extensions.SetEncodedExtension("key1", []byte("1"))
op.Extensions.SetEncodedExtension("key2", []byte("2"))

marshaled, _ := json.Marshal(op)

assert.Equal(string(marshaled), exp, strconv.Itoa(n))
}
}

0 comments on commit a8e1514

Please sign in to comment.