From 325aa46cf223bde4eff46baa1f9478aa3397773d Mon Sep 17 00:00:00 2001 From: Deepak Date: Sat, 9 Jan 2021 21:50:54 -0600 Subject: [PATCH] Adds actions insert to store --- models/action.go | 5 ++ models/err_model_test.go | 4 ++ models/models.go | 1 + models/models_test.go | 8 ++++ routes/actions.go | 56 ++++++++++++++++++++++ routes/route_model_test.go | 11 +++++ store/postgres.go | 30 ++++++++++++ store/postgres_test.go | 98 ++++++++++++++++++++++++++++++++++++++ 8 files changed, 213 insertions(+) diff --git a/models/action.go b/models/action.go index 287a7e7..245f7b2 100644 --- a/models/action.go +++ b/models/action.go @@ -26,3 +26,8 @@ func (m *Model) Action(id int) (*Action, error) { act, err := m.SelectActionByID(id) return act, wrapNotFound(err) } + +// AddAction inserts a given action into the store, returning the generated ActionID. The provided ActionID is ignored. +func (m *Model) AddAction(action *Action) (int, error) { + return m.InsertAction(action) +} diff --git a/models/err_model_test.go b/models/err_model_test.go index 486a965..b800fd1 100644 --- a/models/err_model_test.go +++ b/models/err_model_test.go @@ -12,6 +12,10 @@ func (e *errorStore) SelectActionByID(id int) (*models.Action, error) { return nil, e.error } +func (e *errorStore) InsertAction(action *models.Action) (int, error) { + return 0, e.error +} + func (e *errorStore) SelectPlans() ([]*models.Plan, error) { return nil, e.error } diff --git a/models/models.go b/models/models.go index 19acba9..86e99c0 100644 --- a/models/models.go +++ b/models/models.go @@ -9,6 +9,7 @@ type Store interface { ConnectionLive() error SelectActions() ([]*Action, error) SelectActionByID(id int) (*Action, error) + InsertAction(action *Action) (int, error) SelectPlans() ([]*Plan, error) SelectPlanByID(id int) (*Plan, error) InsertPlan(plan *Plan) (int, error) diff --git a/models/models_test.go b/models/models_test.go index 6990ece..ed832e6 100644 --- a/models/models_test.go +++ b/models/models_test.go @@ -19,6 +19,10 @@ func (ms *multiStore) SelectActionByID(id int) (*models.Action, error) { return ms.actions[0], nil } +func (ms *multiStore) InsertAction(action *models.Action) (int, error) { + return int(action.ActionID), nil +} + func (ms *multiStore) SelectPlans() ([]*models.Plan, error) { return ms.plans, nil } @@ -57,6 +61,10 @@ func TestModelActions(t *testing.T) { assert.Nil(err) assert.EqualValues(3, firstAction.ActionID) + actionID, err := m.AddAction(a1) + assert.Nil(err) + assert.EqualValues(3, actionID) + } func TestModelPlanMethods(t *testing.T) { diff --git a/routes/actions.go b/routes/actions.go index 8be29f8..466f38a 100644 --- a/routes/actions.go +++ b/routes/actions.go @@ -4,6 +4,7 @@ import ( "encoding/json" "gitea.deepak.science/deepak/gogmagog/models" "github.com/go-chi/chi" + "io" "net/http" "strconv" ) @@ -11,6 +12,7 @@ import ( func newActionRouter(m *models.Model) http.Handler { router := chi.NewRouter() router.Get("/", getActionsFunc(m)) + router.Post("/", postActionFunc(m)) router.Get("/{actionid}", getActionByIDFunc(m)) return router } @@ -68,3 +70,57 @@ func getActionByIDFunc(m *models.Model) http.HandlerFunc { } } } + +type createActionResponse struct { + CreatedAction *models.Action `json:"created_action"` + ID int64 `json:"id"` +} + +func postActionFunc(m *models.Model) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + r.Body = http.MaxBytesReader(w, r.Body, 1024) + dec := json.NewDecoder(r.Body) + dec.DisallowUnknownFields() + var a models.Action + err := dec.Decode(&a) + if err != nil { + badRequestError(w, err) + return + } + err = dec.Decode(&struct{}{}) + if err != io.EOF { + badRequestError(w, err) + return + } + + action := &models.Action{ + ActionDescription: a.ActionDescription, + EstimatedChunks: a.EstimatedChunks, + CompletedChunks: a.CompletedChunks, + CompletedOn: a.CompletedOn, + PlanID: a.PlanID, + } + id, err := m.AddAction(action) + if err != nil { + serverError(w, err) + return + } + action, err = m.Action(id) + if err != nil { + serverError(w, err) + return + } + + response := &createActionResponse{ + CreatedAction: action, + ID: int64(id), + } + w.WriteHeader(http.StatusCreated) + w.Header().Add("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(response); err != nil { + serverError(w, err) + } + + } +} diff --git a/routes/route_model_test.go b/routes/route_model_test.go index 17aa962..a177dfb 100644 --- a/routes/route_model_test.go +++ b/routes/route_model_test.go @@ -30,6 +30,10 @@ func (ms *multiStore) SelectActionByID(id int) (*models.Action, error) { return ms.actions[0], nil } +func (ms *multiStore) InsertAction(action *models.Action) (int, error) { + return int(action.ActionID), nil +} + func (ms *multiStore) SelectPlans() ([]*models.Plan, error) { return ms.plans, nil } @@ -79,6 +83,10 @@ func (e *errorStore) SelectActionByID(id int) (*models.Action, error) { return nil, e.error } +func (e *errorStore) InsertAction(action *models.Action) (int, error) { + return 0, e.error +} + func (e *errorStore) SelectPlans() ([]*models.Plan, error) { return nil, e.error } @@ -115,6 +123,9 @@ func (e *onlyCreateStore) SelectActions() ([]*models.Action, error) { func (e *onlyCreateStore) SelectActionByID(id int) (*models.Action, error) { return nil, e.error } +func (e *onlyCreateStore) InsertAction(action *models.Action) (int, error) { + return int(action.ActionID), nil +} func (e *onlyCreateStore) SelectPlans() ([]*models.Plan, error) { return nil, e.error diff --git a/store/postgres.go b/store/postgres.go index a148f6c..5b9cb06 100644 --- a/store/postgres.go +++ b/store/postgres.go @@ -45,6 +45,36 @@ func (store *postgresStore) SelectActionByID(id int) (*models.Action, error) { return &action, nil } +func (store *postgresStore) InsertAction(action *models.Action) (int, error) { + queryString := store.db.Rebind( + `INSERT INTO actions (action_description, + estimated_chunks, + completed_chunks, + completed_on, + plan_id) VALUES (?) RETURNING action_id`, + ) + tx := store.db.MustBegin() + var id int + err := tx.Get( + &id, + queryString, + action.ActionDescription, + action.EstimatedChunks, + action.CompletedChunks, + action.CompletedOn, + action.PlanID, + ) + if err != nil { + tx.Rollback() + return -1, err + } + err = tx.Commit() + if err != nil { + return -1, err + } + return id, nil +} + func (store *postgresStore) SelectPlans() ([]*models.Plan, error) { plans := make([]*models.Plan, 0) err := store.db.Select(&plans, "SELECT plan_id, plan_date FROM plans") diff --git a/store/postgres_test.go b/store/postgres_test.go index 4ea8b0e..799dfc2 100644 --- a/store/postgres_test.go +++ b/store/postgres_test.go @@ -398,3 +398,101 @@ func TestConnectionLive(t *testing.T) { // results assert.Nil(err) } + +func TestInsertAction(t *testing.T) { + // setup + assert := assert.New(t) + + str, mock := getDbMock(t) + completedOn, _ := time.Parse("2006-01-02", "2021-01-01") + action := &models.Action{ + CompletedOn: &completedOn, + EstimatedChunks: 3, + CompletedChunks: 6, + PlanID: 5, + ActionDescription: "testing", + } + + idToUse := 8 + + rows := sqlmock.NewRows([]string{"action_id"}).AddRow(8) + + mock.ExpectBegin() + mock.ExpectQuery("^INSERT INTO actions \\(action_description, estimated_chunks, completed_chunks, completed_on, plan_id\\) VALUES \\(\\$1\\) RETURNING action_id$"). + WithArgs("testing", 3, 6, completedOn, 5). + WillReturnRows(rows) + mock.ExpectCommit() + + // function under test + insertedId, err := str.InsertAction(action) + // check results + assert.Nil(err) + assert.EqualValues(idToUse, insertedId) + if err := mock.ExpectationsWereMet(); err != nil { + t.Errorf("unfulfilled expectations: %s", err) + } + +} + +func TestInsertActionErr(t *testing.T) { + // setup + assert := assert.New(t) + + str, mock := getDbMock(t) + completedOn, _ := time.Parse("2006-01-02", "2021-01-01") + action := &models.Action{ + CompletedOn: &completedOn, + EstimatedChunks: 3, + CompletedChunks: 6, + PlanID: 5, + ActionDescription: "testing", + } + + mock.ExpectBegin() + mock.ExpectQuery("^INSERT INTO actions \\(action_description, estimated_chunks, completed_chunks, completed_on, plan_id\\) VALUES \\(\\$1\\) RETURNING action_id$"). + WithArgs("testing", 3, 6, completedOn, 5). + WillReturnError(fmt.Errorf("example error")) + mock.ExpectRollback() + + // function under test + _, err := str.InsertAction(action) + // check results + assert.NotNil(err) + if err := mock.ExpectationsWereMet(); err != nil { + t.Errorf("unfulfilled expectations: %s", err) + } + +} + +func TestInsertActionCommitErr(t *testing.T) { + // setup + assert := assert.New(t) + + str, mock := getDbMock(t) + completedOn, _ := time.Parse("2006-01-02", "2021-01-01") + action := &models.Action{ + CompletedOn: &completedOn, + EstimatedChunks: 3, + CompletedChunks: 6, + PlanID: 5, + ActionDescription: "testing", + } + idToUse := 8 + + rows := sqlmock.NewRows([]string{"plan_id"}).AddRow(idToUse) + + mock.ExpectBegin() + mock.ExpectQuery("^INSERT INTO actions \\(action_description, estimated_chunks, completed_chunks, completed_on, plan_id\\) VALUES \\(\\$1\\) RETURNING action_id$"). + WithArgs("testing", 3, 6, completedOn, 5). + WillReturnRows(rows) + mock.ExpectCommit().WillReturnError(fmt.Errorf("another error example")) + + // function under test + _, err := str.InsertAction(action) + // check results + assert.NotNil(err) + if err := mock.ExpectationsWereMet(); err != nil { + t.Errorf("unfulfilled expectations: %s", err) + } + +}