Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated get service requests by workflow name API #82

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions handlers/service_request_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package handlers
import (
"clamp-core/models"
"clamp-core/services"
"clamp-core/utils"
"encoding/json"
"errors"
"io/ioutil"
Expand Down Expand Up @@ -157,33 +158,40 @@ func findServiceRequestByWorkflowNameHandler() gin.HandlerFunc {
log.Println("Get service request by workflow name handler")
pageSizeStr := c.Query("pageSize")
pageNumberStr := c.Query("pageNumber")
sortByQuery := c.Query("sortBy")
if pageSizeStr == "" || pageNumberStr == "" {
err := errors.New("page number or page size is not been defined")
prepareErrorResponse(err, c)
return
}
pageNumber, pageNumberErr := strconv.Atoi(pageNumberStr)
pageSize, pageSizeErr := strconv.Atoi(pageSizeStr)
if pageNumberErr != nil || pageSizeErr != nil || pageSize < 0 || pageNumber < 0 {
if pageNumberErr != nil || pageSizeErr != nil || pageSize < utils.MinPageSize || pageNumber < utils.MinPageNumber {
err := errors.New("page number or page size is not in proper format")
prepareErrorResponse(err, c)
return
}
workflowName := c.Param("workflowName")
serviceRequests, err := services.FindServiceRequestByWorkflowName(workflowName, pageNumber, pageSize)
sortByFields, err := models.ParseFromQuery(sortByQuery)
if err != nil {
prepareErrorResponse(err, c)
return
}
c.JSON(http.StatusOK, prepareServiceRequestsResponse(serviceRequests, pageNumber, pageSize))
serviceRequests, totalServiceRequestsCount, err := services.FindServiceRequestByWorkflowName(workflowName, pageNumber, pageSize, sortByFields)
if err != nil {
prepareErrorResponse(err, c)
return
}
c.JSON(http.StatusOK, prepareServiceRequestsResponse(serviceRequests, pageNumber, pageSize, totalServiceRequestsCount))
}
}

func prepareServiceRequestsResponse(serviceRequests []models.ServiceRequest, pageNumber int, pageSize int) models.ServiceRequestPageResponse {
func prepareServiceRequestsResponse(serviceRequests []models.ServiceRequest, pageNumber int, pageSize int, totalServiceRequestsCount int) models.ServiceRequestPageResponse {
response := models.ServiceRequestPageResponse{
ServiceRequests: serviceRequests,
PageNumber: pageNumber,
PageSize: pageSize,
ServiceRequests: serviceRequests,
PageNumber: pageNumber,
PageSize: pageSize,
TotalServiceRequestsCount: totalServiceRequestsCount,
}
return response
}
69 changes: 66 additions & 3 deletions handlers/service_request_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ func TestShouldFindServiceRequestByWorkflowNameByPage(t *testing.T) {
router := setupRouter()
w := httptest.NewRecorder()

req, _ := http.NewRequest("GET", "/serviceRequests/testWorkflow?pageNumber=0&pageSize=1", nil)
req, _ := http.NewRequest("GET", "/serviceRequests/testWorkflow?pageNumber=1&pageSize=1", nil)
router.ServeHTTP(w, req)

bodyStr := w.Body.String()
Expand All @@ -199,14 +199,13 @@ func TestShouldFindServiceRequestByWorkflowNameByPage(t *testing.T) {

assert.Equal(t, 200, w.Code)
assert.NotNil(t, jsonResp)
assert.NotNil(t, jsonResp.ServiceRequests)
}

func TestShouldThrowErrorIfQueryParamsAreNotPassedInServiceRequestByWorkflowName(t *testing.T) {
router := setupRouter()
w := httptest.NewRecorder()

req, _ := http.NewRequest("GET", "/serviceRequests/testWorkflow?pageNumber=0", nil)
req, _ := http.NewRequest("GET", "/serviceRequests/testWorkflow?pageNumber=1", nil)
router.ServeHTTP(w, req)

bodyStr := w.Body.String()
Expand All @@ -233,3 +232,67 @@ func TestShouldThrowErrorIfQueryParamsAreNotValidValuesInServiceRequestByWorkflo
assert.NotNil(t, jsonResp)
assert.Equal(t, "page number or page size is not in proper format", jsonResp.Message)
}

func TestShouldGetServiceRequestsByWorkflowNameAndBySort(t *testing.T) {
CreateWorkflowIfItsAlreadyDoesNotExists()
router := setupRouter()
w := httptest.NewRecorder()

req, _ := http.NewRequest("GET", "/serviceRequests/testWorkflow?pageNumber=1&pageSize=1&sortBy=id:desc", nil)
router.ServeHTTP(w, req)

bodyStr := w.Body.String()
var jsonResp models.ServiceRequestPageResponse
json.Unmarshal([]byte(bodyStr), &jsonResp)

assert.Equal(t, 200, w.Code)
assert.NotNil(t, jsonResp)
}

func TestShouldFailGetServiceRequestsByWorkflowNameWithInvalidSortFields(t *testing.T) {
CreateWorkflowIfItsAlreadyDoesNotExists()
router := setupRouter()
w := httptest.NewRecorder()

req, _ := http.NewRequest("GET", "/serviceRequests/testWorkflow?pageNumber=1&pageSize=1&sortBy=ids:desc", nil)
router.ServeHTTP(w, req)

bodyStr := w.Body.String()
var jsonResp models.ServiceRequestPageResponse
json.Unmarshal([]byte(bodyStr), &jsonResp)

assert.Equal(t, 400, w.Code)
assert.Nil(t, jsonResp.ServiceRequests)
}

func TestShouldFailGetServiceRequestsByWorkflowNameWithInvalidSortQuery(t *testing.T) {
CreateWorkflowIfItsAlreadyDoesNotExists()
router := setupRouter()
w := httptest.NewRecorder()

req, _ := http.NewRequest("GET", "/serviceRequests/testWorkflow?pageNumber=1&pageSize=1&sortBy=id:", nil)
router.ServeHTTP(w, req)

bodyStr := w.Body.String()
var jsonResp models.ServiceRequestPageResponse
json.Unmarshal([]byte(bodyStr), &jsonResp)

assert.Equal(t, 400, w.Code)
assert.Nil(t, jsonResp.ServiceRequests)
}

func TestShouldGetServiceRequestsByWorkflowNameWithTotalServiceRequests(t *testing.T) {
CreateWorkflowIfItsAlreadyDoesNotExists()
router := setupRouter()
w := httptest.NewRecorder()

req, _ := http.NewRequest("GET", "/serviceRequests/testWorkflow?pageNumber=1&pageSize=1&sortBy=id:desc", nil)
router.ServeHTTP(w, req)

bodyStr := w.Body.String()
var jsonResp models.ServiceRequestPageResponse
json.Unmarshal([]byte(bodyStr), &jsonResp)

assert.Equal(t, 200, w.Code)
assert.NotNil(t, jsonResp.TotalServiceRequestsCount)
}
3 changes: 2 additions & 1 deletion handlers/workflow_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package handlers
import (
"clamp-core/models"
"clamp-core/services"
"clamp-core/utils"
"errors"
"fmt"
"log"
Expand Down Expand Up @@ -133,7 +134,7 @@ func getWorkflows() gin.HandlerFunc {
}
pageNumber, pageNumberErr := strconv.Atoi(pageNumberStr)
pageSize, pageSizeErr := strconv.Atoi(pageSizeStr)
if pageNumberErr != nil || pageSizeErr != nil || pageSize < 1 || pageNumber < 1 {
if pageNumberErr != nil || pageSizeErr != nil || pageSize < utils.MinPageSize || pageNumber < utils.MinPageNumber {
err := errors.New("page number or page size is not in proper format")
prepareErrorResponse(err, c)
return
Expand Down
7 changes: 4 additions & 3 deletions models/service_request_page_response.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package models

type ServiceRequestPageResponse struct {
ServiceRequests []ServiceRequest `json:"serviceRequests"`
PageNumber int `json:"pageNumber"`
PageSize int `json:"pageSize"`
ServiceRequests []ServiceRequest `json:"serviceRequests"`
PageNumber int `json:"pageNumber"`
PageSize int `json:"pageSize"`
TotalServiceRequestsCount int `json:"totalServiceRequestsCount"`
}
2 changes: 1 addition & 1 deletion models/sort_fields.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func verifySortValues(key string, value string) bool {
if value != "desc" && value != "asc" {
return false
}
supportedKeys := []string{"id", "name", "created_at"}
supportedKeys := []string{"id", "name", "created_at", "workflow_name", "status"}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tejash-jl We can externalize sort fields to some constants file or env file ??

for _, keyVal := range supportedKeys {
if key == keyVal {
return true
Expand Down
15 changes: 15 additions & 0 deletions models/sort_fields_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,18 @@ func TestParseFromQueryReturnErrForInvalidField(t *testing.T) {
assert.NotNil(t, err)
assert.Equal(t, "Unsupported value provided for sortBy query", err.Error())
}

func TestShouldParse(t *testing.T) {
sortByQuery := `created_at:desc,id:asc,name:desc,`

sortUsing, err := ParseFromQuery(sortByQuery)

assert.Nil(t, err)
assert.Equal(t, 3, len(sortUsing))
assert.Equal(t, "created_at", sortUsing[0].Key)
assert.Equal(t, "desc", sortUsing[0].Order)
assert.Equal(t, "id", sortUsing[1].Key)
assert.Equal(t, "asc", sortUsing[1].Order)
assert.Equal(t, "name", sortUsing[2].Key)
assert.Equal(t, "desc", sortUsing[2].Order)
}
2 changes: 1 addition & 1 deletion repository/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ type DBInterface interface {
FindStepStatusByServiceRequestIDAndStepIDAndStatus(serviceRequestID uuid.UUID, stepID int, status models.Status) (models.StepsStatus, error)
FindAllStepStatusByServiceRequestIDAndStepID(serviceRequestID uuid.UUID, stepID int) ([]models.StepsStatus, error)
GetWorkflows(pageNumber int, pageSize int, sortBy models.SortByFields) ([]models.Workflow, int, error)
FindServiceRequestsByWorkflowName(workflowName string, pageNumber int, pageSize int) ([]models.ServiceRequest, error)
FindServiceRequestsByWorkflowName(workflowName string, pageNumber int, pageSize int, sortBy models.SortByFields) ([]models.ServiceRequest, int, error)
DeleteWorkflowByName(string) error
}

Expand Down
18 changes: 11 additions & 7 deletions repository/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,20 +68,24 @@ type postgres struct {
db *pg.DB
}

func (p *postgres) FindServiceRequestsByWorkflowName(workflowName string, pageNumber int, pageSize int) ([]models.ServiceRequest, error) {
func (p *postgres) FindServiceRequestsByWorkflowName(workflowName string, pageNumber int, pageSize int, sortFields models.SortByFields) ([]models.ServiceRequest, int, error) {
var pgServiceRequests []models.PGServiceRequest
err := p.getDb().Model(&pgServiceRequests).
Where("workflow_name = ?", workflowName).
Limit(pageSize).
Offset(pageNumber).
Select()
query := p.getDb().Model(&pgServiceRequests).Where("workflow_name = ?", workflowName)
for _, sortField := range sortFields {
reference := sortField.Key
order := sortField.Order
query = query.Order(reference + " " + order)
}
totalServiceRequestsCount := 0
totalServiceRequestsCount, err := query.Offset(pageSize * (pageNumber - 1)).
Limit(pageSize).SelectAndCount()
var workflows []models.ServiceRequest
if err == nil {
for _, pgServiceRequest := range pgServiceRequests {
workflows = append(workflows, pgServiceRequest.ToServiceRequest())
}
}
return workflows, err
return workflows, totalServiceRequestsCount, err
}

func (p *postgres) FindAllStepStatusByServiceRequestIDAndStepID(serviceRequestID uuid.UUID, stepID int) ([]models.StepsStatus, error) {
Expand Down
6 changes: 3 additions & 3 deletions services/abstract_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ func (m mockDB) DeleteWorkflowByName(workflowName string) error {
return deleteWorkflowByNameMock(workflowName)
}

func (m mockDB) FindServiceRequestsByWorkflowName(workflowName string, pageNumber int, pageSize int) ([]models.ServiceRequest, error) {
return findServiceRequestsByWorkflowName(workflowName, pageNumber, pageSize)
func (m mockDB) FindServiceRequestsByWorkflowName(workflowName string, pageNumber int, pageSize int, sortBy models.SortByFields) ([]models.ServiceRequest, int, error) {
return findServiceRequestsByWorkflowName(workflowName, pageNumber, pageSize, sortBy)
}

func (m mockDB) GetWorkflows(pageNumber int, pageSize int, sortBy models.SortByFields) ([]models.Workflow, int, error) {
Expand All @@ -29,7 +29,7 @@ func (m mockDB) FindStepStatusByServiceRequestIDAndStepNameAndStatus(serviceRequ
return findStepStatusByServiceRequestIDAndStepNameAndStatusMock(serviceRequestID, stepName, status)
}

var findServiceRequestsByWorkflowName func(workflowName string, pageNumber int, pageSize int) ([]models.ServiceRequest, error)
var findServiceRequestsByWorkflowName func(workflowName string, pageNumber int, pageSize int, sortBy models.SortByFields) ([]models.ServiceRequest, int, error)
var saveServiceRequestMock func(serReq models.ServiceRequest) (models.ServiceRequest, error)
var saveStepStatusMock func(stepStatus models.StepsStatus) (models.StepsStatus, error)
var SaveWorkflowMock func(workflow models.Workflow) (models.Workflow, error)
Expand Down
6 changes: 3 additions & 3 deletions services/service_request_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,11 @@ func SaveServiceRequest(serviceReq models.ServiceRequest) (models.ServiceRequest
}

//FindServiceRequestByWorkflowName fetches all ServiceRequests that are associated to a workflow type
func FindServiceRequestByWorkflowName(workflowName string, pageNumber int, pageSize int) ([]models.ServiceRequest, error) {
func FindServiceRequestByWorkflowName(workflowName string, pageNumber int, pageSize int, sortBy models.SortByFields) ([]models.ServiceRequest, int, error) {
log.Printf("Getting service request by workflow name: %s", workflowName)
serviceRequests, err := repository.GetDB().FindServiceRequestsByWorkflowName(workflowName, pageNumber, pageSize)
serviceRequests, totalServiceRequestsCount, err := repository.GetDB().FindServiceRequestsByWorkflowName(workflowName, pageNumber, pageSize, sortBy)
if err != nil {
log.Printf("Failed to fetch service requests by workflow nam: %s for pageNumber: %d, pageSize: %d", workflowName, pageNumber, pageSize)
}
return serviceRequests, err
return serviceRequests, totalServiceRequestsCount, err
}
8 changes: 5 additions & 3 deletions services/service_request_service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,12 @@ func TestFindServiceRequestsByWorkflowName(t *testing.T) {
serviceReq := models.ServiceRequest{
ID: uuid.UUID{},
}
findServiceRequestsByWorkflowName = func(workflowName string, pageNumber int, pageSize int) ([]models.ServiceRequest, error) {
return []models.ServiceRequest{serviceReq}, nil
findServiceRequestsByWorkflowName = func(workflowName string, pageNumber int, pageSize int, sortBy models.SortByFields) ([]models.ServiceRequest, int, error) {
return []models.ServiceRequest{serviceReq}, 0, nil
}
resp, err := findServiceRequestsByWorkflowName("test", 1, 1)
sortFields := models.SortByFields{{Key: "id", Order: "asc"}}
resp, totalServiceRequestsCount, err := findServiceRequestsByWorkflowName("test", 1, 1, sortFields)
assert.Nil(t, err)
assert.Equal(t, 1, len(resp))
assert.NotNil(t, totalServiceRequestsCount)
}
3 changes: 3 additions & 0 deletions utils/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,7 @@ const ServiceRequestWorkersSize = 100
const ResumeStepResponseChannelSize = 1000
const ResumeStepResponseWorkersSize = 100

const MinPageSize = 1
const MinPageNumber = 1

var MilliSecondsDivisor int64 = 1000000