// GET /api/v0/hub // Params: access_token func ShowHub(w http.ResponseWriter, r *http.Request, c router.Context) error { db, _ := c.Meta["db"].(*sqlx.DB) // Since all is well, get hub(s) from database var h data.Hubs if err := h.SelectByUserId(db, c.Meta["user_id"].(int64)); err != nil { if e, ok := err.(*data.Error); ok { return res.BadRequest(w, res.ErrorMsg{e.Code, e.Desc}) } return err } // prepare oAuth2 access token payload payload := struct { Hubs []string `json:"hub"` }{ h, } return res.OK(w, payload) }
func TestHubSelectByUserId(t *testing.T) { // setup database db := testhelpers.SetupDB(t) // insert new user u := &data.User{ Username: "******", Email: "*****@*****.**", EncryptedPassword: "******", } if err := u.Insert(db); err != nil { t.Error("Failed to insert user to db: %v", u) } h := &data.Hub{ Slug: "earthworm", UserID: 1, } if err := h.Insert(db); err != nil { t.Error("Failed to insert h to db: %v", h) } // query for the inserted hub by userid var h1 data.Hubs if err := h1.SelectByUserId(db, 1); err != nil { t.Error("Failed to get hubs with userid: 1") } if h1[0] != h.Slug { t.Error("Unexpected user record returned: %v", h1) } // query for a non-existing hub var h2 data.Hubs err := h2.SelectByUserId(db, 9999) if err == nil { t.Error("Get should return an error") } e, ok := err.(*data.Error) if !ok { t.Error("Returned error must be of type `data.Error`") } if e.Code != "record_not_found" { t.Error("Error code must be 'record_not_found' but received %s", e.Code) } if e.Desc != "hub not found" { t.Error("Error desc must be 'user not found' but received %s", e.Desc) } // TODO: Add a test case of other errors (eg: db already closed) db.Close() }