File: dynamizer.go

package info (click to toggle)
golang-github-adroll-goamz 0.0~git20170225.0.c5d7d9b-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,520 kB
  • ctags: 2,498
  • sloc: makefile: 41
file content (264 lines) | stat: -rw-r--r-- 6,827 bytes parent folder | download | duplicates (3)
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package dynamizer

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"reflect"
	"runtime"
	"strconv"

	"github.com/cbroglie/mapstructure"
)

// A DynamoAttribute represents the union of possible DynamoDB attribute values.
// See http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html
//
// Since the intention is to use this with JSON documents (or structs
// representing JSON documents), the binary and set types have been omitted.
type DynamoAttribute struct {
	S    *string                     `json:",omitempty"` // pointer so we can represent the zero-value
	N    string                      `json:",omitempty"`
	BOOL *bool                       `json:",omitempty"` // pointer so we can represent the zero-value
	NULL bool                        `json:",omitempty"`
	M    map[string]*DynamoAttribute `json:",omitempty"`
	L    []*DynamoAttribute          `json:",omitempty"`
}

// A DynamoItem represents a the top level item stored in DyanmoDB.
type DynamoItem map[string]*DynamoAttribute

// ToDynamo accepts a map or struct in basic JSON format and converts it to a
// map which can be JSON-encoded into the DynamoDB format.
//
// If in is a struct, we first JSON encode/decode it to get the data as a map.
// This can/should be optimized later.
func ToDynamo(in interface{}) (item DynamoItem, err error) {
	defer func() {
		if r := recover(); r != nil {
			if e, ok := r.(runtime.Error); ok {
				err = e
			} else if s, ok := r.(string); ok {
				err = errors.New(s)
			} else {
				err = r.(error)
			}
			item = nil
		}
	}()

	v := reflect.ValueOf(in)
	switch v.Kind() {
	case reflect.Struct:
		item = dynamizeStruct(in)
	case reflect.Map:
		if v.Type().Key().Kind() != reflect.String {
			return nil, errors.New("item must be a map[string]interface{} or struct (or a non-nil pointer to one), got " + v.Type().String())
		}
		item = dynamizeMap(in)
	case reflect.Ptr:
		if v.IsNil() {
			return nil, errors.New("item must not be nil")
		}
		return ToDynamo(v.Elem().Interface())
	default:
		return nil, errors.New("item must be a map[string]interface{} or struct (or a non-nil pointer to one), got " + v.Type().String())
	}
	return item, nil
}

// FromDynamo takes a map of DynamoDB attributes and converts it into a map or
// struct in basic JSON format.
//
// If v points to a struct, we first convert it to a basic map, then JSON
// encode/decode it to convert to a struct. This can/should be optimized later.
func FromDynamo(item DynamoItem, v interface{}) (err error) {
	defer func() {
		if r := recover(); r != nil {
			if e, ok := r.(runtime.Error); ok {
				err = e
			} else if s, ok := r.(string); ok {
				err = errors.New(s)
			} else {
				err = r.(error)
			}
			item = nil
		}
	}()

	m := make(map[string]interface{})
	for k, v := range item {
		m[k] = undynamize(v)
	}

	// Handle the case where v is already a reflect.Value object representing a
	// struct or map.
	rv, ok := v.(reflect.Value)
	var rt reflect.Type
	if ok {
		rt = rv.Type()
		if !rv.CanAddr() {
			return fmt.Errorf("v is not addressable")
		}
	} else {
		rv = reflect.ValueOf(v)
		if rv.Kind() != reflect.Ptr || rv.IsNil() {
			if rv.IsValid() {
				return fmt.Errorf("v must be a non-nil pointer to a map[string]interface{} or struct (or an addressable reflect.Value), got %s", rv.Type().String())
			} else {
				return fmt.Errorf("v must be a non-nil pointer to a map[string]interface{} or struct (or an addressable reflect.Value), got zero-value")
			}
		}
		rt = rv.Type()
		rv = rv.Elem()
	}

	switch rv.Kind() {
	case reflect.Struct:
		config := &mapstructure.DecoderConfig{
			TagName: "json",
			Result:  v,
		}
		decoder, err := mapstructure.NewDecoder(config)
		if err != nil {
			return err
		}
		return decoder.Decode(m)
	case reflect.Map:
		if rv.Type().Key().Kind() != reflect.String {
			return fmt.Errorf("v must be a non-nil pointer to a map[string]interface{} or struct (or an addressable reflect.Value), got %s", rt.String())
		}
		rv.Set(reflect.ValueOf(m))
	default:
		return fmt.Errorf("v must be a non-nil pointer to a map[string]interface{} or struct (or an addressable reflect.Value), got %s", rt.String())
	}

	return nil
}

func dynamizeStruct(in interface{}) DynamoItem {
	// TODO: We convert structs into basic maps by JSON encoding/decoding. This
	// can be made more efficient by recursing over the struct directly.
	b, err := json.Marshal(in)
	if err != nil {
		panic(err)
	}

	var m map[string]interface{}
	decoder := json.NewDecoder(bytes.NewReader(b))
	decoder.UseNumber()
	err = decoder.Decode(&m)
	if err != nil {
		panic(err)
	}

	return dynamizeMap(m)
}

func dynamizeMap(in interface{}) DynamoItem {
	item := make(DynamoItem)
	m := in.(map[string]interface{})
	for k, v := range m {
		item[k] = dynamize(v)
	}
	return item
}

func dynamize(in interface{}) *DynamoAttribute {
	a := &DynamoAttribute{}

	if in == nil {
		a.NULL = true
		return a
	}

	if m, ok := in.(map[string]interface{}); ok {
		a.M = make(map[string]*DynamoAttribute)
		for k, v := range m {
			a.M[k] = dynamize(v)
		}
		return a
	}

	if l, ok := in.([]interface{}); ok {
		a.L = make([]*DynamoAttribute, len(l))
		for index, v := range l {
			a.L[index] = dynamize(v)
		}
		return a
	}

	// Only primitive types should remain.
	v := reflect.ValueOf(in)
	switch v.Kind() {
	case reflect.Bool:
		a.BOOL = new(bool)
		*a.BOOL = v.Bool()
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		a.N = strconv.FormatInt(v.Int(), 10)
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		a.N = strconv.FormatUint(v.Uint(), 10)
	case reflect.Float32, reflect.Float64:
		a.N = strconv.FormatFloat(v.Float(), 'f', -1, 64)
	case reflect.String:
		if n, ok := in.(json.Number); ok {
			a.N = n.String()
		} else {
			a.S = new(string)
			*a.S = v.String()
		}
	default:
		panic(fmt.Sprintf(`the type %s is not supported`, v.Type().String()))
	}

	return a
}

func undynamize(a *DynamoAttribute) interface{} {
	if a.S != nil {
		return *a.S
	}

	if a.N != "" {
		// Number is tricky b/c we don't know which numeric type to use. Here we
		// simply try the different types from most to least restrictive.
		if n, err := strconv.ParseInt(a.N, 10, 64); err == nil {
			return int(n)
		}
		if n, err := strconv.ParseUint(a.N, 10, 64); err == nil {
			return uint(n)
		}
		n, err := strconv.ParseFloat(a.N, 64)
		if err != nil {
			panic(err)
		}
		return n
	}

	if a.BOOL != nil {
		return *a.BOOL
	}

	if a.NULL {
		return nil
	}

	if a.M != nil {
		m := make(map[string]interface{})
		for k, v := range a.M {
			m[k] = undynamize(v)
		}
		return m
	}

	if a.L != nil {
		l := make([]interface{}, len(a.L))
		for index, v := range a.L {
			l[index] = undynamize(v)
		}
		return l
	}

	panic(fmt.Sprintf("unsupported dynamo attribute %#v", a))
}