You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.1 KiB

  1. package models
  2. import (
  3. "time"
  4. "github.com/arnaucube/gogame/database"
  5. "gopkg.in/mgo.v2/bson"
  6. )
  7. // UserDb is the data in DB
  8. type UserDb struct {
  9. Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
  10. Name string
  11. Password string
  12. Email string
  13. LastUpdated time.Time
  14. Planets []bson.ObjectId
  15. Points int64 // real points are this value / 1000
  16. }
  17. // User is the data in memory, after getting it from DB
  18. type User struct {
  19. db *database.Db
  20. Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
  21. Name string
  22. LastUpdated time.Time
  23. Planets []bson.ObjectId
  24. Points int64
  25. }
  26. func NewUser(db *database.Db, name, password, email string) (*User, error) {
  27. newUser := UserDb{
  28. Id: bson.NewObjectId(),
  29. Name: name,
  30. Password: password,
  31. Email: email,
  32. LastUpdated: time.Now(),
  33. Points: 0,
  34. }
  35. err := db.Users.Insert(newUser)
  36. if err != nil {
  37. return nil, err
  38. }
  39. user := UserDbToUser(db, newUser)
  40. return user, nil
  41. }
  42. func UserDbToUser(db *database.Db, u UserDb) *User {
  43. return &User{
  44. Id: u.Id,
  45. Name: u.Name,
  46. LastUpdated: u.LastUpdated,
  47. db: db,
  48. Planets: u.Planets,
  49. Points: u.Points,
  50. }
  51. }
  52. func (u *User) StoreInDb() error {
  53. err := u.db.Users.Update(bson.M{"_id": u.Id}, bson.M{"$set": bson.M{
  54. "lastupdated": time.Now(),
  55. "planets": u.Planets,
  56. }})
  57. return err
  58. }
  59. func (u *User) GetFromDb() error {
  60. var userDb UserDb
  61. err := u.db.Users.Find(bson.M{"_id": u.Id}).One(&userDb)
  62. if err != nil {
  63. return err
  64. }
  65. u = UserDbToUser(u.db, userDb)
  66. return nil
  67. }
  68. func (u *User) GetPlanets() ([]Planet, error) {
  69. var planets []Planet
  70. err := u.db.Planets.Find(bson.M{"ownerid": u.Id}).All(&planets)
  71. if err != nil {
  72. return planets, err
  73. }
  74. return planets, nil
  75. }
  76. func AddPoints(db *database.Db, userId bson.ObjectId, points int64) error {
  77. var userDb UserDb
  78. err := db.Users.Find(bson.M{"_id": userId}).One(&userDb)
  79. if err != nil {
  80. return err
  81. }
  82. newPoints := userDb.Points + points
  83. err = db.Users.Update(bson.M{"_id": userId}, bson.M{"$set": bson.M{
  84. "points": newPoints,
  85. }})
  86. return err
  87. }