From 14c0d9363594c6e8fa2cd86b924ddd4c52ca543b Mon Sep 17 00:00:00 2001 From: Tobie Morgan Hitchcock Date: Fri, 27 Apr 2018 15:23:58 +0100 Subject: [PATCH] Ensure arrays and objects are always set --- db/merge.go | 4 ++++ util/conv/conv.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/db/merge.go b/db/merge.go index ba8ba6d8..d2ea7439 100644 --- a/db/merge.go +++ b/db/merge.go @@ -295,6 +295,10 @@ func (d *document) mrgFld(ctx context.Context, met method) (err error) { var old = d.initial.Get(key).Data() + // Ensure object and arrays are set + + val = conv.MustBe(fd.Type, val) + // Ensure the field is the correct type if val != nil { diff --git a/util/conv/conv.go b/util/conv/conv.go index bca13ead..ac0e0800 100644 --- a/util/conv/conv.go +++ b/util/conv/conv.go @@ -53,6 +53,37 @@ func toBoolean(str string) (bool, error) { // -------------------------------------------------- +func MustBe(t, obj interface{}) (val interface{}) { + switch t { + default: + return obj + case "array": + return MustBeArray(obj) + case "object": + return MustBeObject(obj) + } +} + +func MustBeArray(obj interface{}) (val interface{}) { + if now, ok := obj.([]interface{}); ok { + val = now + } else { + val = make([]interface{}, 0) + } + return +} + +func MustBeObject(obj interface{}) (val interface{}) { + if now, ok := obj.(map[string]interface{}); ok { + val = now + } else { + val = make(map[string]interface{}) + } + return +} + +// -------------------------------------------------- + func MightBe(obj interface{}) (val interface{}, ok bool) { switch now := obj.(type) { case string: