Skip to content

Commit 675cda3

Browse files
authored
fix(api): unmarshal env last modified date (#5205)
1 parent 9599374 commit 675cda3

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

sdk/environment.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package sdk
22

33
import (
4+
json "encoding/json"
45
"time"
56
)
67

@@ -18,6 +19,46 @@ type Environment struct {
1819
FromRepository string `json:"from_repository,omitempty"`
1920
}
2021

22+
// UnmarshalJSON custom for last modified.
23+
func (e *Environment) UnmarshalJSON(data []byte) error {
24+
var tmp struct {
25+
ID int64 `json:"id"`
26+
Name string `json:"name"`
27+
Variables []Variable `json:"variables"`
28+
ProjectKey string `json:"project_key"`
29+
Created time.Time `json:"created"`
30+
Keys []EnvironmentKey `json:"keys"`
31+
Usage *Usage `json:"usage"`
32+
FromRepository string `json:"from_repository"`
33+
}
34+
35+
if err := json.Unmarshal(data, &tmp); err != nil {
36+
return err
37+
}
38+
e.ID = tmp.ID
39+
e.Name = tmp.Name
40+
e.Variables = tmp.Variables
41+
e.ProjectKey = tmp.ProjectKey
42+
e.Created = tmp.Created
43+
e.Keys = tmp.Keys
44+
e.Usage = tmp.Usage
45+
e.FromRepository = tmp.FromRepository
46+
47+
var v map[string]interface{}
48+
if err := json.Unmarshal(data, &v); err != nil {
49+
return err
50+
}
51+
if lastModifiedNumber, ok := v["last_modified"].(float64); ok {
52+
e.LastModified = time.Unix(int64(lastModifiedNumber), 0)
53+
}
54+
if lastModifiedString, ok := v["last_modified"].(string); ok {
55+
date, _ := time.Parse(time.RFC3339, lastModifiedString)
56+
e.LastModified = date
57+
}
58+
59+
return nil
60+
}
61+
2162
// EnvironmentVariableAudit represents an audit on an environment variable
2263
type EnvironmentVariableAudit struct {
2364
ID int64 `json:"id" yaml:"-" db:"id"`

sdk/environment_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package sdk_test
2+
3+
import (
4+
json "encoding/json"
5+
"fmt"
6+
"testing"
7+
"time"
8+
9+
"github.com/ovh/cds/sdk"
10+
"github.com/stretchr/testify/assert"
11+
"github.com/stretchr/testify/require"
12+
)
13+
14+
func TestEnvironmentUnmarshal(t *testing.T) {
15+
now := time.Unix(time.Now().Unix(), 0)
16+
17+
nowBytes, err := json.Marshal(now)
18+
require.NoError(t, err)
19+
20+
data1 := []byte(fmt.Sprintf("{\"name\":\"one\",\"last_modified\":%s}", nowBytes))
21+
data2 := []byte(fmt.Sprintf("{\"name\":\"two\",\"last_modified\":%d}", now.Unix()))
22+
23+
var one sdk.Environment
24+
require.NoError(t, json.Unmarshal(data1, &one))
25+
assert.Equal(t, "one", one.Name)
26+
assert.True(t, now.Equal(one.LastModified))
27+
28+
var two sdk.Environment
29+
require.NoError(t, json.Unmarshal(data2, &two))
30+
assert.Equal(t, "two", two.Name)
31+
assert.True(t, now.Equal(two.LastModified))
32+
}

0 commit comments

Comments
 (0)