// Should return the user with the given username, or throw an Entity not found error func TestGetUser(t *testing.T) { ctx, done, err := aetest.NewContext() if err != nil { t.Fatal(err) } defer done() key := datastore.NewKey(ctx, "User", "testertim", 0, nil) if _, err := datastore.Put(ctx, key, &models.User{FirstName: "Tim"}); err != nil { t.Fatal(err) } user := &models.User{Username: "******"} if err = repositories.GetUser(ctx, user); err == nil || err.Error() != "datastore: no such entity" { t.Errorf("Error: %v; want datastore: no such entity", err) } user.Username = "******" err = repositories.GetUser(ctx, user) if err != nil { t.Fatal(err) } if firstName, want := user.FirstName, "Tim"; firstName != want { t.Errorf("User First Name %d, want %d", firstName, want) } if username, want := user.Username, "testertim"; username != want { t.Errorf("Username %d, want %d", username, want) } }
// Creates a user with the given username, so long as that username is not already taken func StoreUser(w http.ResponseWriter, r *http.Request, params httprouter.Params) { user := &models.User{Username: params.ByName("username")} ctx := appengine.NewContext(r) _, err := repositories.GetUser(ctx, user) if err == nil { http.Error(w, "Username already exists!", http.StatusConflict) return } user = &models.User{ Username: username, FirstName: r.FormValue("firstName"), LastName: r.FormValue("lastName"), Email: r.FormValue("email"), } err = repositories.StoreUser(ctx, user) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) response, err := json.Marshal(user) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Write(response) }
// Gets a user with the given username from the repository, // or returns a 404 error if not found. func GetUser(w http.ResponseWriter, r *http.Request, params httprouter.Params) { ctx := appengine.NewContext(r) user := &models.User{Username: params.ByName("username")} user, err := repositories.GetUser(ctx, user) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } response, err := json.Marshal(user) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(response) }