Merge pull request #392 from dapr/cosmos4
#377 - cosmos deserialization issue
This commit is contained in:
commit
b1c8dd5e31
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue