diff pkg/models/importbase.go @ 2044:ea0b62b7656b unify_imports

Imports: Unified JSON marshaling of times and durations in imports.
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Fri, 25 Jan 2019 17:54:02 +0100
parents d29ac997eb34
children c8cc875d271c
line wrap: on
line diff
--- a/pkg/models/importbase.go	Fri Jan 25 17:29:43 2019 +0100
+++ b/pkg/models/importbase.go	Fri Jan 25 17:54:02 2019 +0100
@@ -26,16 +26,20 @@
 	// CronSpec is a string containing a cron line.
 	CronSpec string
 
+	ConfigTime struct{ time.Time }
+
+	ConfigDuration struct{ time.Duration }
+
 	EmailType struct {
 		Email bool `json:"send-email,omitempty"`
 	}
 
 	QueueConfigurationType struct {
 		EmailType
-		Trys      *int           `json:"trys,omitempty"`
-		WaitRetry *time.Duration `json:"wait-retry,omitempty"`
-		Due       *time.Time     `json:"due,omitempty"`
-		Cron      *CronSpec      `json:"cron,omitempty"`
+		Trys      *int            `json:"trys,omitempty"`
+		WaitRetry *ConfigDuration `json:"wait-retry,omitempty"`
+		Due       *ConfigTime     `json:"due,omitempty"`
+		Cron      *CronSpec       `json:"cron,omitempty"`
 	}
 
 	URLType struct {
@@ -70,6 +74,45 @@
 	return et
 }
 
+func (cd *ConfigDuration) UnmarshalJSON(data []byte) error {
+	var s string
+	if err := json.Unmarshal(data, &s); err != nil {
+		return err
+	}
+	dur, err := time.ParseDuration(s)
+	if err != nil {
+		return err
+	}
+	if dur < 0 {
+		return errors.New("duration has to be none negative.")
+	}
+	*cd = ConfigDuration{dur}
+	return nil
+}
+
+func (cd *ConfigDuration) MarshalJSON() ([]byte, error) {
+	s := cd.Duration.String()
+	return json.Marshal([]byte(s))
+}
+
+func (ct *ConfigTime) UnmarshalJSON(data []byte) error {
+	var s string
+	if err := json.Unmarshal(data, &s); err != nil {
+		return err
+	}
+	t, err := time.Parse(common.TimeFormat, s)
+	if err != nil {
+		return err
+	}
+	*ct = ConfigTime{t}
+	return nil
+}
+
+func (ct *ConfigTime) MarshalJSON() ([]byte, error) {
+	s := ct.Time.Format(common.TimeFormat)
+	return json.Marshal([]byte(s))
+}
+
 // UnmarshalJSON checks if the incoming string is a valid cron line.
 func (cs *CronSpec) UnmarshalJSON(data []byte) error {
 	var spec string
@@ -103,10 +146,10 @@
 		attrs.SetInt("trys", *qct.Trys)
 	}
 	if qct.WaitRetry != nil {
-		attrs.SetDuration("wait-retry", *qct.WaitRetry)
+		attrs.SetDuration("wait-retry", qct.WaitRetry.Duration)
 	}
 	if qct.Due != nil {
-		attrs.SetTime("due", *qct.Due)
+		attrs.SetTime("due", qct.Due.Time)
 	}
 	return nil
 }