-
Notifications
You must be signed in to change notification settings - Fork 0
/
seed.go
59 lines (53 loc) · 1.61 KB
/
seed.go
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
package videos_seed
import (
"context"
"encoding/json"
"github.com/go-redis/redis/v8"
"io/ioutil"
"os"
)
func (videosSeed *VideosSeed) SeedVideosData(client *redis.Client, ctx context.Context) {
videos, err := videosSeed.getVideosFromJson()
if err != nil {
videosSeed.Logger.Errorw("Error while trying to get videos from JSON", err)
return
}
videosSeed.Logger.Infow("Videos fetched successfully from the JSON", videos)
for _, video := range videos {
videoJson, err := json.Marshal(video)
if err != nil {
videosSeed.Logger.Errorw("Error while marshalling video to JSON", err)
return
}
err = client.Set(ctx, video.Id, videoJson, 0).Err()
if err != nil {
videosSeed.Logger.Errorw("Error while Updating database with video", err)
return
}
}
}
func (videosSeed *VideosSeed) getVideosFromJson() ([]Videos, error) {
// Open our jsonFile
jsonFile, err := os.Open("videos-seed/videos.json")
// if we os.Open returns an error then handle it
if err != nil {
videosSeed.Logger.Errorw("Error while opening the videos json file", err)
return []Videos{}, err
}
videosSeed.Logger.Infow("Successfully Opened videos.json")
// defer the closing of our jsonFile so that we can parse it later on
defer func(jsonFile *os.File) {
err := jsonFile.Close()
if err != nil {
videosSeed.Logger.Errorw("Error while closing the videos json file", err)
}
}(jsonFile)
byteValue, _ := ioutil.ReadAll(jsonFile)
var videos []Videos
err = json.Unmarshal(byteValue, &videos)
if err != nil {
videosSeed.Logger.Errorw("Error while unmarshalling the json file", err)
return []Videos{}, err
}
return videos, nil
}