From 1f62e375e70f3f144a4b6887883cb9cbb47f680d Mon Sep 17 00:00:00 2001 From: Hoang Date: Mon, 8 Nov 2021 08:52:10 +0700 Subject: [PATCH] add update method --- action_update.go | 67 ++++++++++++++++++++++++++++++++++++++++++++++++ validate.go | 28 ++++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 action_update.go diff --git a/action_update.go b/action_update.go new file mode 100644 index 0000000..bc1fb02 --- /dev/null +++ b/action_update.go @@ -0,0 +1,67 @@ +package devicemngmt + +import ( + "context" + "fmt" + + "github.com/Selly-Modules/logger" + "go.mongodb.org/mongo-driver/bson" +) + +// UpdateOptions ... +type UpdateOptions struct { + UserAgent string + AppVersion string + IP string + FCMToken string + AuthToken string + Language string + Model string + Manufacturer string +} + +// UpdateByDeviceID ... +func (s Service) UpdateByDeviceID(deviceID string, payload UpdateOptions) error { + var ( + ctx = context.Background() + col = s.getDeviceCollection() + cond = bson.M{ + "deviceID": deviceID, + } + ) + + // Validate payload + err := payload.validate() + if err != nil { + return err + } + + // Setup update data + updateData := bson.M{ + "$set": bson.M{ + "osName": getOSName(payload.UserAgent), + "osVersion": getOSVersion(payload.UserAgent), + "ip": payload.IP, + "language": getLanguage(payload.Language), + "authToken": payload.AuthToken, + "fcmToken": payload.FCMToken, + "model": payload.Model, + "manufacturer": payload.Manufacturer, + "appVersion": payload.AppVersion, + "isMobile": payload.AppVersion != "", + "lastActivatedAt": now(), + }, + } + + // Update + _, err = col.UpdateOne(ctx, cond, updateData) + if err != nil { + logger.Error("devicemngt - updateByDeviceID", logger.LogData{ + "deviceID": deviceID, + "err": err.Error(), + }) + return fmt.Errorf("error when update device: %s", err.Error()) + } + + return nil +} diff --git a/validate.go b/validate.go index 476badd..7dbb1c2 100644 --- a/validate.go +++ b/validate.go @@ -49,3 +49,31 @@ func (co CreateOptions) validate() error { return nil } + +func (uo UpdateOptions) validate() error { + // UserAgent + if uo.UserAgent == "" { + logger.Error("devicemngt - Update: no userAgent data", logger.LogData{ + "payload": uo, + }) + return errors.New("no userAgent data") + } + + // IP + if uo.IP == "" { + logger.Error("devicemngt - Update: no ip data", logger.LogData{ + "payload": uo, + }) + return errors.New("no ip data") + } + + // AuthToken + if uo.AuthToken == "" { + logger.Error("devicemngt - Update: no authToken data", logger.LogData{ + "payload": uo, + }) + return errors.New("no authToken data") + } + + return nil +}