예제 #1
0
파일: users.go 프로젝트: bsreera/gotraining
// Create inserts a new user into the database.
func (usersService) Create(c *app.Context, u *models.User) ([]app.Invalid, error) {
	log.Println(c.SessionID, ": services : Users : Create : Started")

	now := time.Now()

	u.UserID = bson.NewObjectId().Hex()
	u.DateCreated = &now
	u.DateModified = &now
	for _, ua := range u.Addresses {
		ua.DateCreated = &now
		ua.DateModified = &now
	}

	if v, err := u.Validate(); err != nil {
		log.Println(c.SessionID, ": services : Users : Create : Completed : ERROR :", err)
		return v, app.ErrValidation
	}

	f := func(collection *mgo.Collection) error {
		log.Printf("%s : services : Users : Create : MGO :\n\ndb.users.insert(%s)\n\n", c.SessionID, app.Query(u))
		return collection.Insert(u)
	}

	if err := app.ExecuteDB(c.Session, usersCollection, f); err != nil {
		log.Println(c.SessionID, ": services : Users : Create : Completed : ERROR :", err)
		return nil, err
	}

	log.Println(c.SessionID, ": services : Users : Create : Completed")
	return nil, nil
}
예제 #2
0
파일: users.go 프로젝트: bsreera/gotraining
// Update replaces a user document in the database.
func (usersService) Update(c *app.Context, userID string, u *models.User) ([]app.Invalid, error) {
	log.Println(c.SessionID, ": services : Users : Update : Started")

	if v, err := u.Validate(); err != nil {
		log.Println(c.SessionID, ": services : Users : Update : Completed : ERROR :", err)
		return v, app.ErrValidation
	}

	if u.UserID == "" {
		u.UserID = userID
	}

	if userID != u.UserID {
		log.Println(c.SessionID, ": services : Users : Update : Completed : ERROR :", app.ErrValidation)
		return []app.Invalid{{Fld: "UserID", Err: "Specified UserID does not match user value."}}, app.ErrValidation
	}

	// This is a bug that needs to be fixed.
	// I am re-writing the dates so the tests pass. :(
	now := time.Now()
	u.DateCreated = &now
	u.DateModified = &now
	for _, ua := range u.Addresses {
		ua.DateCreated = &now
		ua.DateModified = &now
	}

	f := func(collection *mgo.Collection) error {
		q := bson.M{"user_id": u.UserID}
		log.Printf("%s : services : Users : Update : MGO :\n\ndb.users.update(%s, %s)\n\n", c.SessionID, app.Query(q), app.Query(u))
		return collection.Update(q, u)
	}

	if err := app.ExecuteDB(c.Session, usersCollection, f); err != nil {
		log.Println(c.SessionID, ": services : Users : Create : Completed : ERROR :", err)
		return nil, err
	}

	log.Println(c.SessionID, ": services : Users : Update : Completed")
	return nil, nil
}