Merge pull request #392 from dapr/cosmos4

#377 - cosmos deserialization issue
This commit is contained in:
Leon Mai 2020-07-14 14:55:45 -07:00 committed by GitHub
commit b1c8dd5e31
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 33 additions and 1 deletions

View File

@ -6,6 +6,7 @@
package cosmosdb
import (
"bytes"
"encoding/json"
"errors"
"fmt"
@ -43,6 +44,16 @@ type CosmosItem struct {
PartitionKey string `json:"partitionKey"`
}
// CosmosItemWithRawMessage is a version of CosmosItem with a Value of RawMessage so this field
// is not marshalled. If it is marshalled it will end up in a form that
// cannot be unmarshalled. This type is used when SetRequest.Value arrives as bytes.
type CosmosItemWithRawMessage struct {
documentdb.Document
ID string `json:"id"`
Value jsoniter.RawMessage `json:"value"`
PartitionKey string `json:"partitionKey"`
}
type storedProcedureDefinition struct {
ID string `json:"id"`
Body string `json:"body"`
@ -196,7 +207,20 @@ func (c *StateStore) Set(req *state.SetRequest) error {
options = append(options, documentdb.ConsistencyLevel(documentdb.Eventual))
}
_, err = c.client.UpsertDocument(c.collection.Self, CosmosItem{ID: req.Key, Value: req.Value, PartitionKey: partitionKey}, options...)
b, ok := req.Value.([]uint8)
if ok {
// data arrived in bytes and already json. Don't marshal the Value field again.
item := CosmosItemWithRawMessage{ID: req.Key, Value: b, PartitionKey: partitionKey}
var marshalled []byte
marshalled, err = convertToJSONWithoutEscapes(item)
if err != nil {
return err
}
_, err = c.client.UpsertDocument(c.collection.Self, marshalled, options...)
} else {
// data arrived as non-bytes, just pass it through.
_, err = c.client.UpsertDocument(c.collection.Self, CosmosItem{ID: req.Key, Value: req.Value, PartitionKey: partitionKey}, options...)
}
if err != nil {
return err
@ -332,3 +356,11 @@ func populatePartitionMetadata(key string, requestMetadata map[string]string) st
}
return key
}
func convertToJSONWithoutEscapes(t interface{}) ([]byte, error) {
buffer := &bytes.Buffer{}
encoder := jsoniter.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
err := encoder.Encode(t)
return buffer.Bytes(), err
}