Update seen service to allow overriding values

This commit is contained in:
Ben Toogood
2021-02-04 12:47:19 +00:00
parent 6ca55ba18d
commit d67554b63c
3 changed files with 29 additions and 6 deletions

View File

@@ -6,6 +6,7 @@ import (
"gorm.io/gorm"
"github.com/google/uuid"
"github.com/micro/micro/v3/service/errors"
"github.com/micro/micro/v3/service/logger"
pb "github.com/micro/services/seen/proto"
@@ -25,6 +26,7 @@ type Seen struct {
}
type SeenInstance struct {
ID string
UserID string `gorm:"uniqueIndex:user_resource"`
ResourceID string `gorm:"uniqueIndex:user_resource"`
ResourceType string `gorm:"uniqueIndex:user_resource"`
@@ -49,14 +51,22 @@ func (s *Seen) Set(ctx context.Context, req *pb.SetRequest, rsp *pb.SetResponse)
req.Timestamp = timestamppb.New(time.Now())
}
// write the object to the store
err := s.DB.Create(SeenInstance{
// find the resource
instance := SeenInstance{
UserID: req.UserId,
ResourceID: req.ResourceId,
ResourceType: req.ResourceType,
Timestamp: req.Timestamp.AsTime(),
}).Error
if err != nil {
}
if err := s.DB.Where(&instance).First(&instance).Error; err == gorm.ErrRecordNotFound {
instance.ID = uuid.New().String()
} else if err != nil {
logger.Errorf("Error with store: %v", err)
return ErrStore
}
// update the resource
instance.Timestamp = req.Timestamp.AsTime()
if err := s.DB.Save(&instance).Error; err != nil {
logger.Errorf("Error with store: %v", err)
return ErrStore
}

View File

@@ -74,6 +74,13 @@ func TestSet(t *testing.T) {
ResourceID: uuid.New().String(),
ResourceType: "message",
},
{
Name: "WithUpdatedTimetamp",
UserID: uuid.New().String(),
ResourceID: uuid.New().String(),
ResourceType: "message",
Timestamp: timestamppb.New(time.Now().Add(time.Minute * -3)),
},
}
h := testHandler(t)
@@ -164,6 +171,12 @@ func TestRead(t *testing.T) {
ResourceType string
Timestamp *timestamppb.Timestamp
}{
{
UserID: "user-1",
ResourceID: "message-1",
ResourceType: "message",
Timestamp: timestamppb.New(tn.Add(time.Minute * -10)),
},
{
UserID: "user-1",
ResourceID: "message-1",

View File

@@ -35,7 +35,7 @@ func main() {
}
// Register handler
pb.RegisterSeenHandler(srv.Server(), &handler.Seen{DB: db})
pb.RegisterSeenHandler(srv.Server(), &handler.Seen{DB: db.Debug()})
// Run service
if err := srv.Run(); err != nil {