add update method

This commit is contained in:
Hoang 2021-11-08 08:52:10 +07:00
parent 1631f921b0
commit 1f62e375e7
2 changed files with 95 additions and 0 deletions

67
action_update.go Normal file
View File

@ -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
}

View File

@ -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
}