From a3c67f13d2fbbb47647c2bc0082566f7cbae5b1e Mon Sep 17 00:00:00 2001
From: Volker Schukai <volker.schukai@schukai.com>
Date: Wed, 6 Dec 2023 01:45:13 +0100
Subject: [PATCH] fix: parse duration in json #35

---
 schedule-interval_test.go | 29 +++++++++++++++++++++++++++++
 scheduler.go              | 11 ++++++++++-
 2 files changed, 39 insertions(+), 1 deletion(-)

diff --git a/schedule-interval_test.go b/schedule-interval_test.go
index 198e571..ecde52f 100644
--- a/schedule-interval_test.go
+++ b/schedule-interval_test.go
@@ -4,6 +4,7 @@
 package jobqueue
 
 import (
+	"encoding/json"
 	"github.com/stretchr/testify/assert"
 	"gopkg.in/yaml.v3"
 	"testing"
@@ -29,3 +30,31 @@ interval: "1h30m"
 	expectedInterval, _ := time.ParseDuration("1h30m")
 	assert.Equal(t, expectedInterval, sp.Delay, "the interval should be parsed correctly")
 }
+
+// TestUnmarshalJSON tests the UnmarshalJSON method
+func TestUnmarshalJSON(t *testing.T) {
+	// Example JSON string representing SchedulerPersistence
+	jsonStr := `{
+		"time": "2023-12-06T15:04:05Z",
+		"interval": "1h30m"
+	}`
+
+	// Create an instance of SchedulerPersistence
+	sp := SchedulerPersistence{}
+
+	// Unmarshal the JSON string into the sp structure
+	err := json.Unmarshal([]byte(jsonStr), &sp)
+	assert.NoError(t, err, "Unmarshalling should not produce an error")
+
+	// Verify that the Time field is correctly parsed
+	expectedTime, _ := time.Parse(time.RFC3339, "2023-12-06T15:04:05Z")
+	if sp.Time != nil {
+		assert.Equal(t, expectedTime, *sp.Time, "Time should be correctly parsed")
+	} else {
+		t.Error("Time field is nil, but it should not be")
+	}
+
+	// Verify that the Delay field is correctly parsed
+	expectedInterval, _ := time.ParseDuration("1h30m")
+	assert.Equal(t, expectedInterval, sp.Delay, "Interval should be correctly parsed")
+}
diff --git a/scheduler.go b/scheduler.go
index 2f882ef..942218c 100644
--- a/scheduler.go
+++ b/scheduler.go
@@ -41,7 +41,8 @@ func (sp *SchedulerPersistence) UnmarshalJSON(data []byte) error {
 	// Anonymous structure to avoid endless recursion
 	type Alias SchedulerPersistence
 	aux := &struct {
-		Time *string `json:"time,omitempty"`
+		Time     *string `json:"time,omitempty"`
+		Interval *string `json:"interval,omitempty"` // Ensure this matches the JSON field name
 		*Alias
 	}{
 		Alias: (*Alias)(sp),
@@ -66,6 +67,14 @@ func (sp *SchedulerPersistence) UnmarshalJSON(data []byte) error {
 		sp.Time = &t
 	}
 
+	if aux.Interval != nil {
+		d, err := time.ParseDuration(*aux.Interval)
+		if err != nil {
+			return err
+		}
+		sp.Delay = d
+	}
+
 	return nil
 }
 
-- 
GitLab