diff --git a/api/swagger/docs.go b/api/swagger/docs.go index d81850a4..a03dcc39 100644 --- a/api/swagger/docs.go +++ b/api/swagger/docs.go @@ -7469,6 +7469,9 @@ const docTemplate = `{ "domain.GetProjectMembersResponse": { "type": "object", "properties": { + "pagination": { + "$ref": "#/definitions/domain.PaginationResponse" + }, "projectMembers": { "type": "array", "items": { @@ -7534,6 +7537,9 @@ const docTemplate = `{ "domain.GetProjectsResponse": { "type": "object", "properties": { + "pagination": { + "$ref": "#/definitions/domain.PaginationResponse" + }, "projects": { "type": "array", "items": { diff --git a/api/swagger/swagger.json b/api/swagger/swagger.json index e512de5e..23c41d4f 100644 --- a/api/swagger/swagger.json +++ b/api/swagger/swagger.json @@ -7463,6 +7463,9 @@ "domain.GetProjectMembersResponse": { "type": "object", "properties": { + "pagination": { + "$ref": "#/definitions/domain.PaginationResponse" + }, "projectMembers": { "type": "array", "items": { @@ -7528,6 +7531,9 @@ "domain.GetProjectsResponse": { "type": "object", "properties": { + "pagination": { + "$ref": "#/definitions/domain.PaginationResponse" + }, "projects": { "type": "array", "items": { diff --git a/api/swagger/swagger.yaml b/api/swagger/swagger.yaml index 447ebfd8..91ba3f8e 100644 --- a/api/swagger/swagger.yaml +++ b/api/swagger/swagger.yaml @@ -1380,6 +1380,8 @@ definitions: type: object domain.GetProjectMembersResponse: properties: + pagination: + $ref: '#/definitions/domain.PaginationResponse' projectMembers: items: $ref: '#/definitions/domain.ProjectMemberResponse' @@ -1421,6 +1423,8 @@ definitions: type: object domain.GetProjectsResponse: properties: + pagination: + $ref: '#/definitions/domain.PaginationResponse' projects: items: $ref: '#/definitions/domain.ProjectResponse' diff --git a/internal/delivery/http/alert.go b/internal/delivery/http/alert.go index 3591c4dd..4e0c78e4 100644 --- a/internal/delivery/http/alert.go +++ b/internal/delivery/http/alert.go @@ -95,11 +95,7 @@ func (h *AlertHandler) GetAlerts(w http.ResponseWriter, r *http.Request) { } urlParams := r.URL.Query() - pg, err := pagination.NewPagination(&urlParams) - if err != nil { - ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) - return - } + pg := pagination.NewPagination(&urlParams) // convert status for i, filter := range pg.GetFilters() { if filter.Column == "status" { @@ -143,18 +139,9 @@ func (h *AlertHandler) GetAlerts(w http.ResponseWriter, r *http.Request) { } } - if err := serializer.Map(*pg, &out.Pagination); err != nil { + if out.Pagination, err = pg.Response(); err != nil { log.InfoWithContext(r.Context(), err) } - /* - outFilters := make([]domain.FilterResponse, len(pg.Filters)) - for j, filter := range pg.Filters { - if err := serializer.Map(filter, &outFilters[j]); err != nil { - log.InfoWithContext(r.Context(), err) - } - } - out.Pagination.Filters = outFilters - */ ResponseJSON(w, r, http.StatusOK, out) } diff --git a/internal/delivery/http/app-group.go b/internal/delivery/http/app-group.go index 1efd767a..84a22bee 100644 --- a/internal/delivery/http/app-group.go +++ b/internal/delivery/http/app-group.go @@ -82,11 +82,7 @@ func (h *AppGroupHandler) GetAppGroups(w http.ResponseWriter, r *http.Request) { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("Invalid clusterId"), "C_INVALID_CLUSTER_ID", "")) return } - pg, err := pagination.NewPagination(&urlParams) - if err != nil { - ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) - return - } + pg := pagination.NewPagination(&urlParams) appGroups, err := h.usecase.Fetch(r.Context(), domain.ClusterId(clusterId), pg) if err != nil { @@ -103,7 +99,7 @@ func (h *AppGroupHandler) GetAppGroups(w http.ResponseWriter, r *http.Request) { } } - if err := serializer.Map(*pg, &out.Pagination); err != nil { + if out.Pagination, err = pg.Response(); err != nil { log.InfoWithContext(r.Context(), err) } diff --git a/internal/delivery/http/app-serve-app.go b/internal/delivery/http/app-serve-app.go index b2bd74d0..75b20722 100644 --- a/internal/delivery/http/app-serve-app.go +++ b/internal/delivery/http/app-serve-app.go @@ -253,12 +253,7 @@ func (h *AppServeAppHandler) GetAppServeApps(w http.ResponseWriter, r *http.Requ ErrorJSON(w, r, err) return } - pg, err := pagination.NewPagination(&urlParams) - if err != nil { - ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) - return - } - + pg := pagination.NewPagination(&urlParams) apps, err := h.usecase.GetAppServeApps(organizationId, showAll, pg) if err != nil { log.ErrorWithContext(r.Context(), "Failed to get Failed to get app-serve-apps ", err) @@ -269,7 +264,7 @@ func (h *AppServeAppHandler) GetAppServeApps(w http.ResponseWriter, r *http.Requ var out domain.GetAppServeAppsResponse out.AppServeApps = apps - if err := serializer.Map(*pg, &out.Pagination); err != nil { + if out.Pagination, err = pg.Response(); err != nil { log.InfoWithContext(r.Context(), err) } @@ -452,11 +447,7 @@ func (h *AppServeAppHandler) GetAppServeAppTasksByAppId(w http.ResponseWriter, r } urlParams := r.URL.Query() - pg, err := pagination.NewPagination(&urlParams) - if err != nil { - ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) - return - } + pg := pagination.NewPagination(&urlParams) tasks, err := h.usecase.GetAppServeAppTasks(appId, pg) if err != nil { @@ -468,7 +459,7 @@ func (h *AppServeAppHandler) GetAppServeAppTasksByAppId(w http.ResponseWriter, r var out domain.GetAppServeAppTasksResponse out.AppServeAppTasks = tasks - if err := serializer.Map(*pg, &out.Pagination); err != nil { + if out.Pagination, err = pg.Response(); err != nil { log.InfoWithContext(r.Context(), err) } diff --git a/internal/delivery/http/audit.go b/internal/delivery/http/audit.go index 8cdb6924..a262445e 100644 --- a/internal/delivery/http/audit.go +++ b/internal/delivery/http/audit.go @@ -63,12 +63,7 @@ func (h *AuditHandler) GetAudits(w http.ResponseWriter, r *http.Request) { } urlParams := r.URL.Query() - pg, err := pagination.NewPagination(&urlParams) - if err != nil { - ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) - return - } - + pg := pagination.NewPagination(&urlParams) audits, err := h.usecase.Fetch(r.Context(), organizationId, pg) if err != nil { ErrorJSON(w, r, err) diff --git a/internal/delivery/http/cloud-account.go b/internal/delivery/http/cloud-account.go index dfce7a78..0548625e 100644 --- a/internal/delivery/http/cloud-account.go +++ b/internal/delivery/http/cloud-account.go @@ -94,11 +94,7 @@ func (h *CloudAccountHandler) GetCloudAccounts(w http.ResponseWriter, r *http.Re } urlParams := r.URL.Query() - pg, err := pagination.NewPagination(&urlParams) - if err != nil { - ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) - return - } + pg := pagination.NewPagination(&urlParams) cloudAccounts, err := h.usecase.Fetch(r.Context(), organizationId, pg) if err != nil { ErrorJSON(w, r, err) @@ -114,7 +110,7 @@ func (h *CloudAccountHandler) GetCloudAccounts(w http.ResponseWriter, r *http.Re } } - if err := serializer.Map(*pg, &out.Pagination); err != nil { + if out.Pagination, err = pg.Response(); err != nil { log.InfoWithContext(r.Context(), err) } diff --git a/internal/delivery/http/cluster.go b/internal/delivery/http/cluster.go index 5cd1848a..e953cf84 100644 --- a/internal/delivery/http/cluster.go +++ b/internal/delivery/http/cluster.go @@ -43,11 +43,7 @@ func (h *ClusterHandler) GetClusters(w http.ResponseWriter, r *http.Request) { urlParams := r.URL.Query() organizationId := urlParams.Get("organizationId") - pg, err := pagination.NewPagination(&urlParams) - if err != nil { - ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) - return - } + pg := pagination.NewPagination(&urlParams) clusters, err := h.usecase.Fetch(r.Context(), organizationId, pg) if err != nil { ErrorJSON(w, r, err) @@ -63,7 +59,7 @@ func (h *ClusterHandler) GetClusters(w http.ResponseWriter, r *http.Request) { } } - if err := serializer.Map(*pg, &out.Pagination); err != nil { + if out.Pagination, err = pg.Response(); err != nil { log.InfoWithContext(r.Context(), err) } diff --git a/internal/delivery/http/organization.go b/internal/delivery/http/organization.go index 1d90f6a0..038a1a1e 100644 --- a/internal/delivery/http/organization.go +++ b/internal/delivery/http/organization.go @@ -91,12 +91,7 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. // @Security JWT func (h *OrganizationHandler) GetOrganizations(w http.ResponseWriter, r *http.Request) { urlParams := r.URL.Query() - pg, err := pagination.NewPagination(&urlParams) - if err != nil { - ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) - return - } - + pg := pagination.NewPagination(&urlParams) organizations, err := h.usecase.Fetch(pg) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) @@ -116,7 +111,7 @@ func (h *OrganizationHandler) GetOrganizations(w http.ResponseWriter, r *http.Re log.InfoWithContext(r.Context(), organization) } - if err := serializer.Map(*pg, &out.Pagination); err != nil { + if out.Pagination, err = pg.Response(); err != nil { log.InfoWithContext(r.Context(), err) } diff --git a/internal/delivery/http/project.go b/internal/delivery/http/project.go index a354cbb7..eb51a81d 100644 --- a/internal/delivery/http/project.go +++ b/internal/delivery/http/project.go @@ -8,6 +8,7 @@ import ( "github.com/google/uuid" "github.com/openinfradev/tks-api/internal/middleware/auth/request" + "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/serializer" "github.com/gorilla/mux" @@ -168,20 +169,28 @@ func (p ProjectHandler) GetProjects(w http.ResponseWriter, r *http.Request) { onlyMyProject = true } + pg := pagination.NewPagination(&urlParams) + // get myUserId from login component requestUserInfo, ok := request.UserFrom(r.Context()) myUserId := requestUserInfo.GetUserId().String() - pr, err := p.usecase.GetProjects(organizationId, myUserId, onlyMyProject) + pr, err := p.usecase.GetProjects(organizationId, myUserId, onlyMyProject, pg) if err != nil { log.ErrorWithContext(r.Context(), "Failed to retrieve projects ", err) ErrorJSON(w, r, err) return } + var out domain.GetProjectsResponse + out.Projects = pr + if out.Pagination, err = pg.Response(); err != nil { + log.InfoWithContext(r.Context(), err) + } + if pr == nil { ResponseJSON(w, r, http.StatusNotFound, domain.GetProjectsResponse{}) } else { - ResponseJSON(w, r, http.StatusOK, pr) + ResponseJSON(w, r, http.StatusOK, out) } } @@ -483,7 +492,9 @@ func (p ProjectHandler) AddProjectMember(w http.ResponseWriter, r *http.Request) return } - pns, err := p.usecase.GetProjectNamespaces(organizationId, projectId) + urlParams := r.URL.Query() + pg := pagination.NewPagination(&urlParams) + pns, err := p.usecase.GetProjectNamespaces(organizationId, projectId, pg) if err != nil { log.Error(err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) @@ -660,7 +671,8 @@ func (p ProjectHandler) GetProjectMembers(w http.ResponseWriter, r *http.Request return } - pms, err := p.usecase.GetProjectMembers(projectId, query) + pg := pagination.NewPagination(&urlParams) + pms, err := p.usecase.GetProjectMembers(projectId, query, pg) if err != nil { log.ErrorWithContext(r.Context(), "Failed to get project members ", err) ErrorJSON(w, r, err) @@ -692,6 +704,10 @@ func (p ProjectHandler) GetProjectMembers(w http.ResponseWriter, r *http.Request } out = domain.GetProjectMembersResponse{ProjectMembers: pmrs} + if out.Pagination, err = pg.Response(); err != nil { + log.InfoWithContext(r.Context(), err) + } + ResponseJSON(w, r, http.StatusOK, out) } @@ -776,7 +792,7 @@ func (p ProjectHandler) RemoveProjectMember(w http.ResponseWriter, r *http.Reque } // tasks for keycloak & k8s - pns, err := p.usecase.GetProjectNamespaces(organizationId, projectId) + pns, err := p.usecase.GetProjectNamespaces(organizationId, projectId, nil) if err != nil { log.Error(err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) @@ -839,7 +855,7 @@ func (p ProjectHandler) RemoveProjectMembers(w http.ResponseWriter, r *http.Requ } // tasks for keycloak & k8s - pns, err := p.usecase.GetProjectNamespaces(organizationId, projectId) + pns, err := p.usecase.GetProjectNamespaces(organizationId, projectId, nil) if err != nil { log.Error(err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) @@ -926,7 +942,7 @@ func (p ProjectHandler) UpdateProjectMemberRole(w http.ResponseWriter, r *http.R return } - pns, err := p.usecase.GetProjectNamespaces(organizationId, projectId) + pns, err := p.usecase.GetProjectNamespaces(organizationId, projectId, nil) if err != nil { log.Error(err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) @@ -1003,7 +1019,7 @@ func (p ProjectHandler) UpdateProjectMembersRole(w http.ResponseWriter, r *http. return } - pns, err := p.usecase.GetProjectNamespaces(organizationId, projectId) + pns, err := p.usecase.GetProjectNamespaces(organizationId, projectId, nil) if err != nil { log.Error(err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) @@ -1197,7 +1213,9 @@ func (p ProjectHandler) GetProjectNamespaces(w http.ResponseWriter, r *http.Requ return } - pns, err := p.usecase.GetProjectNamespaces(organizationId, projectId) + urlParams := r.URL.Query() + pg := pagination.NewPagination(&urlParams) + pns, err := p.usecase.GetProjectNamespaces(organizationId, projectId, pg) if err != nil { log.ErrorWithContext(r.Context(), "Failed to get project namespaces.", err) ErrorJSON(w, r, err) diff --git a/internal/delivery/http/stack-template.go b/internal/delivery/http/stack-template.go index 4e699d35..419a48e6 100644 --- a/internal/delivery/http/stack-template.go +++ b/internal/delivery/http/stack-template.go @@ -56,12 +56,7 @@ func (h *StackTemplateHandler) CreateStackTemplate(w http.ResponseWriter, r *htt // @Security JWT func (h *StackTemplateHandler) GetStackTemplates(w http.ResponseWriter, r *http.Request) { urlParams := r.URL.Query() - pg, err := pagination.NewPagination(&urlParams) - if err != nil { - ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) - return - } - + pg := pagination.NewPagination(&urlParams) stackTemplates, err := h.usecase.Fetch(r.Context(), pg) if err != nil { ErrorJSON(w, r, err) diff --git a/internal/delivery/http/stack.go b/internal/delivery/http/stack.go index 1ec8987d..225a678d 100644 --- a/internal/delivery/http/stack.go +++ b/internal/delivery/http/stack.go @@ -112,11 +112,7 @@ func (h *StackHandler) GetStacks(w http.ResponseWriter, r *http.Request) { } urlParams := r.URL.Query() - pg, err := pagination.NewPagination(&urlParams) - if err != nil { - ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) - return - } + pg := pagination.NewPagination(&urlParams) stacks, err := h.usecase.Fetch(r.Context(), organizationId, pg) if err != nil { ErrorJSON(w, r, err) @@ -137,7 +133,7 @@ func (h *StackHandler) GetStacks(w http.ResponseWriter, r *http.Request) { } } - if err := serializer.Map(*pg, &out.Pagination); err != nil { + if out.Pagination, err = pg.Response(); err != nil { log.InfoWithContext(r.Context(), err) } diff --git a/internal/delivery/http/user.go b/internal/delivery/http/user.go index 85ad3ce4..1d21bdab 100644 --- a/internal/delivery/http/user.go +++ b/internal/delivery/http/user.go @@ -176,11 +176,7 @@ func (u UserHandler) List(w http.ResponseWriter, r *http.Request) { } urlParams := r.URL.Query() - pg, err := pagination.NewPagination(&urlParams) - if err != nil { - ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) - return - } + pg := pagination.NewPagination(&urlParams) users, err := u.usecase.ListWithPagination(r.Context(), organizationId, pg) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) @@ -196,7 +192,7 @@ func (u UserHandler) List(w http.ResponseWriter, r *http.Request) { } } - if err := serializer.Map(*pg, &out.Pagination); err != nil { + if out.Pagination, err = pg.Response(); err != nil { log.InfoWithContext(r.Context(), err) } diff --git a/internal/pagination/pagination.go b/internal/pagination/pagination.go index 69975e9c..956257e5 100644 --- a/internal/pagination/pagination.go +++ b/internal/pagination/pagination.go @@ -1,7 +1,6 @@ package pagination import ( - "fmt" "net/url" "strconv" "strings" @@ -151,87 +150,88 @@ func (p *Pagination) Response() (out domain.PaginationResponse, err error) { return out, err } -func NewPagination(urlParams *url.Values) (*Pagination, error) { - pg := NewDefaultPagination() +func NewPagination(urlParams *url.Values) *Pagination { + pg := newDefaultPagination() - for key, value := range *urlParams { - switch key { - case SORT_COLUMN: - if value[0] != "" { - pg.SortColumn = value[0] - } - case SORT_ORDER: - if value[0] != "" { - pg.SortOrder = value[0] - } - case PAGE_NUMBER: - if value[0] != "" { - pg.Page, _ = strconv.Atoi(value[0]) - } - case PAGE_SIZE: - if value[0] == "" { - if limitNum, err := strconv.Atoi(value[0]); err == nil { - pg.Limit = limitNum + if urlParams != nil { + for key, value := range *urlParams { + switch key { + case SORT_COLUMN: + if value[0] != "" { + pg.SortColumn = value[0] } - } - case COMBINED_FILTER: - if len(value[0]) > 0 { - //"combinedFilter=key1,key2:value" - filterArray := strings.Split(value[0], ":") - if len(filterArray) == 2 { - keys := strings.Split(helper.ToSnakeCase(strings.Replace(filterArray[0], "[]", "", -1)), ",") - value := filterArray[1] - - pg.CombinedFilter = CombinedFilter{ - Columns: keys, - Value: value, + case SORT_ORDER: + if value[0] != "" { + pg.SortOrder = value[0] + } + case PAGE_NUMBER: + if value[0] != "" { + pg.Page, _ = strconv.Atoi(value[0]) + } + case PAGE_SIZE: + if value[0] == "" { + if limitNum, err := strconv.Atoi(value[0]); err == nil { + pg.Limit = limitNum } - } else { - return nil, fmt.Errorf("Invalid query string : combinedFilter ") } - } - case FILTER, FILTER_ARRAY, OR, OR_ARRAY: - for _, filterValue := range value { - arr := strings.Split(filterValue, "|") - - column := arr[0] - releation := "" - arrColumns := strings.Split(column, ".") - if len(arrColumns) > 1 { - releation = arrColumns[0] - column = arrColumns[1] + case COMBINED_FILTER: + if len(value[0]) > 0 { + //"combinedFilter=key1,key2:value" + filterArray := strings.Split(value[0], ":") + if len(filterArray) == 2 { + keys := strings.Split(helper.ToSnakeCase(strings.Replace(filterArray[0], "[]", "", -1)), ",") + value := filterArray[1] + + pg.CombinedFilter = CombinedFilter{ + Columns: keys, + Value: value, + } + } else { + return nil + } } + case FILTER, FILTER_ARRAY, OR, OR_ARRAY: + for _, filterValue := range value { + arr := strings.Split(filterValue, "|") + + column := arr[0] + releation := "" + arrColumns := strings.Split(column, ".") + if len(arrColumns) > 1 { + releation = arrColumns[0] + column = arrColumns[1] + } - trimmedStr := strings.Trim(arr[1], "[]") - values := strings.Split(trimmedStr, ",") + trimmedStr := strings.Trim(arr[1], "[]") + values := strings.Split(trimmedStr, ",") - op := "$cont" - if len(arr) == 3 { - op = arr[2] - } + op := "$cont" + if len(arr) == 3 { + op = arr[2] + } - or := false - if key == OR || key == OR_ARRAY { - or = true - } + or := false + if key == OR || key == OR_ARRAY { + or = true + } - pg.Filters = append(pg.Filters, Filter{ - Column: helper.ToSnakeCase(strings.Replace(column, "[]", "", -1)), - Relation: releation, - Operator: op, - Values: values, - Or: or, - }) + pg.Filters = append(pg.Filters, Filter{ + Column: helper.ToSnakeCase(strings.Replace(column, "[]", "", -1)), + Relation: releation, + Operator: op, + Values: values, + Or: or, + }) + } } } } - pg.MakePaginationRequest() - return pg, nil + return pg } -func NewDefaultPagination() *Pagination { +func newDefaultPagination() *Pagination { return &Pagination{ SortColumn: "created_at", SortOrder: "DESC", diff --git a/internal/repository/alert.go b/internal/repository/alert.go index f1ffd971..0db9a350 100644 --- a/internal/repository/alert.go +++ b/internal/repository/alert.go @@ -1,8 +1,6 @@ package repository import ( - "fmt" - "math" "time" "github.com/google/uuid" @@ -108,24 +106,18 @@ func (r *AlertRepository) GetByName(organizationId string, name string) (out dom func (r *AlertRepository) Fetch(organizationId string, pg *pagination.Pagination) (out []domain.Alert, err error) { var alerts []Alert if pg == nil { - pg = pagination.NewDefaultPagination() + pg = pagination.NewPagination(nil) } - filterFunc := CombinedGormFilter("alerts", pg.GetFilters(), pg.CombinedFilter) - db := filterFunc(r.db.Model(&Alert{}). + _, res := pg.Fetch(r.db.Model(&Alert{}). Preload("AlertActions", func(db *gorm.DB) *gorm.DB { return db.Order("created_at ASC") }).Preload("AlertActions.Taker"). Preload("Cluster", "status = 2"). Preload("Organization"). Joins("join clusters on clusters.id = alerts.cluster_id AND clusters.status = 2"). - Where("alerts.organization_id = ?", organizationId)) + Where("alerts.organization_id = ?", organizationId), &alerts) - db.Count(&pg.TotalRows) - - pg.TotalPages = int(math.Ceil(float64(pg.TotalRows) / float64(pg.Limit))) - orderQuery := fmt.Sprintf("%s %s", pg.SortColumn, pg.SortOrder) - res := db.Offset(pg.GetOffset()).Limit(pg.GetLimit()).Order(orderQuery).Find(&alerts) if res.Error != nil { return nil, res.Error } diff --git a/internal/repository/app-group.go b/internal/repository/app-group.go index e999ae99..be160e53 100644 --- a/internal/repository/app-group.go +++ b/internal/repository/app-group.go @@ -2,7 +2,6 @@ package repository import ( "fmt" - "math" "github.com/google/uuid" "gorm.io/datatypes" @@ -80,20 +79,11 @@ func (c *Application) BeforeCreate(tx *gorm.DB) (err error) { func (r *AppGroupRepository) Fetch(clusterId domain.ClusterId, pg *pagination.Pagination) (out []domain.AppGroup, err error) { var appGroups []AppGroup if pg == nil { - pg = pagination.NewDefaultPagination() + pg = pagination.NewPagination(nil) } - filterFunc := CombinedGormFilter("app_groups", pg.GetFilters(), pg.CombinedFilter) - db := filterFunc(r.db.Model(&AppGroup{}). - Where("cluster_id = ?", clusterId)) - db.Count(&pg.TotalRows) - - r.db.Model(&AppGroup{}). - Where("cluster_id = ?", clusterId).Where("id").Where("app_groups.status").Where("app_groups.deleted") - - pg.TotalPages = int(math.Ceil(float64(pg.TotalRows) / float64(pg.Limit))) - orderQuery := fmt.Sprintf("%s %s", pg.SortColumn, pg.SortOrder) - res := db.Offset(pg.GetOffset()).Limit(pg.GetLimit()).Order(orderQuery).Find(&appGroups) + _, res := pg.Fetch(r.db.Model(&AppGroup{}). + Where("cluster_id = ?", clusterId), &appGroups) if res.Error != nil { return nil, res.Error } diff --git a/internal/repository/app-serve-app.go b/internal/repository/app-serve-app.go index f761b6a7..50c97b45 100644 --- a/internal/repository/app-serve-app.go +++ b/internal/repository/app-serve-app.go @@ -2,7 +2,6 @@ package repository import ( "fmt" - "math" "time" "github.com/openinfradev/tks-api/internal/pagination" @@ -64,18 +63,12 @@ func (r *AppServeAppRepository) CreateTask( func (r *AppServeAppRepository) GetAppServeApps(organizationId string, showAll bool, pg *pagination.Pagination) (apps []domain.AppServeApp, err error) { var clusters []Cluster if pg == nil { - pg = pagination.NewDefaultPagination() + pg = pagination.NewPagination(nil) } - // TODO: should return different records based on showAll param - filterFunc := CombinedGormFilter("app_serve_apps", pg.GetFilters(), pg.CombinedFilter) - db := filterFunc(r.db.Model(&domain.AppServeApp{}). - Where("app_serve_apps.organization_id = ? AND status <> 'DELETE_SUCCESS'", organizationId)) - db.Count(&pg.TotalRows) - - pg.TotalPages = int(math.Ceil(float64(pg.TotalRows) / float64(pg.Limit))) - orderQuery := fmt.Sprintf("%s %s", pg.SortColumn, pg.SortOrder) - res := db.Offset(pg.GetOffset()).Limit(pg.GetLimit()).Order(orderQuery).Find(&apps) + // TODO: should return different records based on showAll param + _, res := pg.Fetch(r.db.Model(&domain.AppServeApp{}). + Where("app_serve_apps.organization_id = ? AND status <> 'DELETE_SUCCESS'", organizationId), &clusters) if res.Error != nil { return nil, fmt.Errorf("error while finding appServeApps with organizationId: %s", organizationId) } @@ -132,17 +125,11 @@ func (r *AppServeAppRepository) GetAppServeAppById(appId string) (*domain.AppSer func (r *AppServeAppRepository) GetAppServeAppTasksByAppId(appId string, pg *pagination.Pagination) (tasks []domain.AppServeAppTask, err error) { if pg == nil { - pg = pagination.NewDefaultPagination() + pg = pagination.NewPagination(nil) } - filterFunc := CombinedGormFilter("app_serve_app_tasks", pg.GetFilters(), pg.CombinedFilter) - db := filterFunc(r.db.Model(&domain.AppServeAppTask{}). - Where("app_serve_app_tasks.app_serve_app_id = ?", appId)) - db.Count(&pg.TotalRows) - - pg.TotalPages = int(math.Ceil(float64(pg.TotalRows) / float64(pg.Limit))) - orderQuery := fmt.Sprintf("%s %s", pg.SortColumn, pg.SortOrder) - res := db.Offset(pg.GetOffset()).Limit(pg.GetLimit()).Order(orderQuery).Find(&tasks) + _, res := pg.Fetch(r.db.Model(&domain.AppServeAppTask{}). + Where("app_serve_app_tasks.app_serve_app_id = ?", appId), &tasks) if res.Error != nil { return nil, fmt.Errorf("Error while finding tasks with appId: %s", appId) } diff --git a/internal/repository/audit.go b/internal/repository/audit.go index bb0f97a2..5e2d684c 100644 --- a/internal/repository/audit.go +++ b/internal/repository/audit.go @@ -66,7 +66,7 @@ func (r *AuditRepository) Fetch(organizationId string, pg *pagination.Pagination var audits []Audit if pg == nil { - pg = pagination.NewDefaultPagination() + pg = pagination.NewPagination(nil) } db := r.db.Model(&Audit{}).Preload(clause.Associations).Where("organization_id = ?", organizationId) diff --git a/internal/repository/cloud-account.go b/internal/repository/cloud-account.go index 786e9f53..a6dd6102 100644 --- a/internal/repository/cloud-account.go +++ b/internal/repository/cloud-account.go @@ -2,7 +2,6 @@ package repository import ( "fmt" - "math" "github.com/google/uuid" "gorm.io/gorm" @@ -99,17 +98,11 @@ func (r *CloudAccountRepository) GetByAwsAccountId(awsAccountId string) (out dom func (r *CloudAccountRepository) Fetch(organizationId string, pg *pagination.Pagination) (out []domain.CloudAccount, err error) { var cloudAccounts []CloudAccount if pg == nil { - pg = pagination.NewDefaultPagination() + pg = pagination.NewPagination(nil) } - filterFunc := CombinedGormFilter("cloud_accounts", pg.GetFilters(), pg.CombinedFilter) - db := filterFunc(r.db.Model(&CloudAccount{}). + _, res := pg.Fetch(r.db.Model(&CloudAccount{}). Preload(clause.Associations). - Where("organization_id = ? AND status != ?", organizationId, domain.CloudAccountStatus_DELETED)) - db.Count(&pg.TotalRows) - - pg.TotalPages = int(math.Ceil(float64(pg.TotalRows) / float64(pg.Limit))) - orderQuery := fmt.Sprintf("%s %s", pg.SortColumn, pg.SortOrder) - res := db.Offset(pg.GetOffset()).Limit(pg.GetLimit()).Order(orderQuery).Find(&cloudAccounts) + Where("organization_id = ? AND status != ?", organizationId, domain.CloudAccountStatus_DELETED), &cloudAccounts) if res.Error != nil { return nil, res.Error } diff --git a/internal/repository/cluster.go b/internal/repository/cluster.go index df6a7213..66de2205 100644 --- a/internal/repository/cluster.go +++ b/internal/repository/cluster.go @@ -2,7 +2,6 @@ package repository import ( "fmt" - "math" "github.com/google/uuid" "gorm.io/gorm" @@ -111,19 +110,14 @@ func (r *ClusterRepository) WithTrx(trxHandle *gorm.DB) IClusterRepository { func (r *ClusterRepository) Fetch(pg *pagination.Pagination) (out []domain.Cluster, err error) { var clusters []Cluster if pg == nil { - pg = pagination.NewDefaultPagination() + pg = pagination.NewPagination(nil) } - filterFunc := CombinedGormFilter("clusters", pg.GetFilters(), pg.CombinedFilter) - db := filterFunc(r.db.Model(&Cluster{})) - db.Count(&pg.TotalRows) - pg.TotalPages = int(math.Ceil(float64(pg.TotalRows) / float64(pg.Limit))) - - orderQuery := fmt.Sprintf("%s %s", pg.SortColumn, pg.SortOrder) - res := db.Offset(pg.GetOffset()).Limit(pg.GetLimit()).Order(orderQuery).Find(&clusters) + _, res := pg.Fetch(r.db, &clusters) if res.Error != nil { return nil, res.Error } + for _, cluster := range clusters { outCluster := reflectCluster(cluster) out = append(out, outCluster) @@ -134,21 +128,15 @@ func (r *ClusterRepository) Fetch(pg *pagination.Pagination) (out []domain.Clust func (r *ClusterRepository) FetchByOrganizationId(organizationId string, userId uuid.UUID, pg *pagination.Pagination) (out []domain.Cluster, err error) { var clusters []Cluster if pg == nil { - pg = pagination.NewDefaultPagination() + pg = pagination.NewPagination(nil) } - pg.SortColumn = "created_at" - pg.SortOrder = "DESC" - filterFunc := CombinedGormFilter("clusters", pg.GetFilters(), pg.CombinedFilter) - db := filterFunc(r.db.Model(&Cluster{}). + + _, res := pg.Fetch(r.db.Model(&Cluster{}). Preload(clause.Associations). Joins("left outer join cluster_favorites on clusters.id = cluster_favorites.cluster_id AND cluster_favorites.user_id = ?", userId). - Where("organization_id = ? AND status != ?", organizationId, domain.ClusterStatus_DELETED)) + Where("organization_id = ? AND status != ?", organizationId, domain.ClusterStatus_DELETED). + Order("cluster_favorites.cluster_id"), &clusters) - db.Count(&pg.TotalRows) - pg.TotalPages = int(math.Ceil(float64(pg.TotalRows) / float64(pg.Limit))) - - orderQuery := fmt.Sprintf("%s %s", pg.SortColumn, pg.SortOrder) - res := db.Offset(pg.GetOffset()).Limit(pg.GetLimit()).Order("cluster_favorites.cluster_id").Order(orderQuery).Find(&clusters) if res.Error != nil { return nil, res.Error } @@ -157,26 +145,16 @@ func (r *ClusterRepository) FetchByOrganizationId(organizationId string, userId out = append(out, outCluster) } - //log.Info(helper.ModelToJson(clusters)) return } func (r *ClusterRepository) FetchByCloudAccountId(cloudAccountId uuid.UUID, pg *pagination.Pagination) (out []domain.Cluster, err error) { var clusters []Cluster if pg == nil { - pg = pagination.NewDefaultPagination() + pg = pagination.NewPagination(nil) } - pg.SortColumn = "created_at" - pg.SortOrder = "DESC" - filterFunc := CombinedGormFilter("clusters", pg.GetFilters(), pg.CombinedFilter) - db := filterFunc(r.db.Model(&Cluster{}).Preload("CloudAccount"). - Where("cloud_account_id = ?", cloudAccountId)) - - db.Count(&pg.TotalRows) - pg.TotalPages = int(math.Ceil(float64(pg.TotalRows) / float64(pg.Limit))) - - orderQuery := fmt.Sprintf("%s %s", pg.SortColumn, pg.SortOrder) - res := db.Offset(pg.GetOffset()).Limit(pg.GetLimit()).Order(orderQuery).Find(&clusters) + _, res := pg.Fetch(r.db.Model(&Cluster{}).Preload("CloudAccount"). + Where("cloud_account_id = ?", cloudAccountId), &clusters) if res.Error != nil { return nil, res.Error } diff --git a/internal/repository/organization.go b/internal/repository/organization.go index 75cc2e7a..e37fc7e4 100644 --- a/internal/repository/organization.go +++ b/internal/repository/organization.go @@ -1,9 +1,6 @@ package repository import ( - "fmt" - "math" - "github.com/google/uuid" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/serializer" @@ -76,19 +73,14 @@ func (r *OrganizationRepository) Fetch(pg *pagination.Pagination) (*[]domain.Org var organizations []Organization var out []domain.Organization if pg == nil { - pg = pagination.NewDefaultPagination() + pg = pagination.NewPagination(nil) } - filterFunc := CombinedGormFilter("organizations", pg.GetFilters(), pg.CombinedFilter) - db := filterFunc(r.db.Model(&Organization{})) - db.Count(&pg.TotalRows) - - pg.TotalPages = int(math.Ceil(float64(pg.TotalRows) / float64(pg.Limit))) - orderQuery := fmt.Sprintf("%s %s", pg.SortColumn, pg.SortOrder) - res := db.Offset(pg.GetOffset()).Limit(pg.GetLimit()).Order(orderQuery).Find(&organizations) + _, res := pg.Fetch(r.db, &organizations) if res.Error != nil { return nil, res.Error } + for _, organization := range organizations { outOrganization := r.reflect(organization) out = append(out, outOrganization) diff --git a/internal/repository/project.go b/internal/repository/project.go index 6802f0dd..c042cdc2 100644 --- a/internal/repository/project.go +++ b/internal/repository/project.go @@ -2,7 +2,10 @@ package repository import ( "database/sql" + "github.com/google/uuid" + + "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/pkg/domain" "github.com/openinfradev/tks-api/pkg/log" "github.com/pkg/errors" @@ -11,8 +14,8 @@ import ( type IProjectRepository interface { CreateProject(p *domain.Project) (string, error) - GetProjects(organizationId string, userId uuid.UUID) ([]domain.ProjectResponse, error) - GetProjectsByUserId(organizationId string, userId uuid.UUID) ([]domain.ProjectResponse, error) + GetProjects(organizationId string, userId uuid.UUID, pg *pagination.Pagination) ([]domain.ProjectResponse, error) + GetProjectsByUserId(organizationId string, userId uuid.UUID, pg *pagination.Pagination) ([]domain.ProjectResponse, error) GetProjectById(organizationId string, projectId string) (*domain.Project, error) GetProjectByIdAndLeader(organizationId string, projectId string) (*domain.Project, error) GetProjectByName(organizationId string, projectName string) (*domain.Project, error) @@ -21,8 +24,8 @@ type IProjectRepository interface { GetProjectRoleByName(name string) (*domain.ProjectRole, error) GetProjectRoleById(id string) (*domain.ProjectRole, error) AddProjectMember(*domain.ProjectMember) (string, error) - GetProjectMembersByProjectId(projectId string) ([]domain.ProjectMember, error) - GetProjectMembersByProjectIdAndRoleName(projectId string, memberRole string) ([]domain.ProjectMember, error) + GetProjectMembersByProjectId(projectId string, pg *pagination.Pagination) ([]domain.ProjectMember, error) + GetProjectMembersByProjectIdAndRoleName(projectId string, memberRole string, pg *pagination.Pagination) ([]domain.ProjectMember, error) GetProjectMemberCountByProjectId(projectId string) (*domain.GetProjectMemberCountResponse, error) GetProjectMemberById(projectMemberId string) (*domain.ProjectMember, error) GetProjectMemberByUserId(projectId string, projectUserId string) (pm *domain.ProjectMember, err error) @@ -30,7 +33,7 @@ type IProjectRepository interface { UpdateProjectMemberRole(pm *domain.ProjectMember) error CreateProjectNamespace(organizationId string, pn *domain.ProjectNamespace) error GetProjectNamespaceByName(organizationId string, projectId string, stackId string, projectNamespace string) (*domain.ProjectNamespace, error) - GetProjectNamespaces(organizationId string, projectId string) ([]domain.ProjectNamespace, error) + GetProjectNamespaces(organizationId string, projectId string, pg *pagination.Pagination) ([]domain.ProjectNamespace, error) GetProjectNamespaceByPrimaryKey(organizationId string, projectId string, projectNamespace string, stackId string) (*domain.ProjectNamespace, error) UpdateProjectNamespace(pn *domain.ProjectNamespace) error DeleteProjectNamespace(organizationId string, projectId string, projectNamespace string, stackId string) error @@ -57,7 +60,10 @@ func (r *ProjectRepository) CreateProject(p *domain.Project) (string, error) { return p.ID, nil } -func (r *ProjectRepository) GetProjects(organizationId string, userId uuid.UUID) (pr []domain.ProjectResponse, err error) { +func (r *ProjectRepository) GetProjects(organizationId string, userId uuid.UUID, pg *pagination.Pagination) (pr []domain.ProjectResponse, err error) { + if pg == nil { + pg = pagination.NewPagination(nil) + } res := r.db.Raw(""+ "select distinct p.id as id, p.organization_id as organization_id, p.name as name, p.description as description, p.created_at as created_at, "+ " true as is_my_project, pm.project_role_id as project_role_id, pm.pr_name as project_role_name, "+ @@ -127,17 +133,15 @@ func (r *ProjectRepository) GetProjects(organizationId string, userId uuid.UUID) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { log.Info("Cannot find project") - return nil, nil - } else { - log.Error(res.Error) - return nil, res.Error } } - return pr, nil } -func (r *ProjectRepository) GetProjectsByUserId(organizationId string, userId uuid.UUID) (pr []domain.ProjectResponse, err error) { +func (r *ProjectRepository) GetProjectsByUserId(organizationId string, userId uuid.UUID, pg *pagination.Pagination) (pr []domain.ProjectResponse, err error) { + if pg == nil { + pg = pagination.NewPagination(nil) + } res := r.db.Raw(""+ "select p.id as id, p.organization_id as organization_id, p.name as name, p.description as description, p.created_at as created_at, "+ " true as is_my_project, pm.project_role_id as project_role_id, pm.pr_name as project_role_name, "+ @@ -299,14 +303,14 @@ func (r *ProjectRepository) AddProjectMember(pm *domain.ProjectMember) (string, return pm.ID, nil } -func (r *ProjectRepository) GetProjectMembersByProjectId(projectId string) (pms []domain.ProjectMember, err error) { - //res := r.db.Preload("ProjectUser"). - // Joins("ProjectRole").Where("project_id = ?", projectId).Find(&pms) - res := r.db.Joins("ProjectUser"). +func (r *ProjectRepository) GetProjectMembersByProjectId(projectId string, pg *pagination.Pagination) (pms []domain.ProjectMember, err error) { + if pg == nil { + pg = pagination.NewPagination(nil) + } + _, res := pg.Fetch(r.db.Joins("ProjectUser"). Joins("ProjectRole"). Where("project_members.project_id = ?", projectId). - Order("project_members.created_at ASC"). - Find(&pms) + Order("project_members.created_at ASC"), &pms) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { log.Info("Cannot find project member") @@ -320,13 +324,15 @@ func (r *ProjectRepository) GetProjectMembersByProjectId(projectId string) (pms return pms, nil } -func (r *ProjectRepository) GetProjectMembersByProjectIdAndRoleName(projectId string, memberRole string) (pms []domain.ProjectMember, err error) { - res := r.db.Joins("ProjectUser"). - //Joins("ProjectRole"). - //Find(&pms, "project_members.project_id = ? and \"ProjectRole\".name = ?", projectId, memberRole) +func (r *ProjectRepository) GetProjectMembersByProjectIdAndRoleName(projectId string, memberRole string, pg *pagination.Pagination) (pms []domain.ProjectMember, err error) { + if pg == nil { + pg = pagination.NewPagination(nil) + } + _, res := pg.Fetch(r.db.Joins("ProjectUser"). InnerJoins("ProjectRole", r.db.Where(&domain.ProjectRole{Name: memberRole})). Order("project_members.created_at ASC"). - Find(&pms, "project_members.project_id = ?", projectId) + Where("project_members.project_id = ?", projectId), &pms) + if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { log.Info("Cannot find project member") @@ -467,10 +473,12 @@ func (r *ProjectRepository) GetProjectNamespaceByName(organizationId string, pro return pn, nil } -func (r *ProjectRepository) GetProjectNamespaces(organizationId string, projectId string) (pns []domain.ProjectNamespace, err error) { - res := r.db.Where("project_id = ?", projectId). - Preload("Stack"). - Find(&pns) +func (r *ProjectRepository) GetProjectNamespaces(organizationId string, projectId string, pg *pagination.Pagination) (pns []domain.ProjectNamespace, err error) { + if pg == nil { + pg = pagination.NewPagination(nil) + } + _, res := pg.Fetch(r.db.Where("project_id = ?", projectId). + Preload("Stack"), &pns) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { log.Info("Not found project namespaces") diff --git a/internal/repository/stack-template.go b/internal/repository/stack-template.go index 54f52b79..4d3004c8 100644 --- a/internal/repository/stack-template.go +++ b/internal/repository/stack-template.go @@ -75,27 +75,9 @@ func (r *StackTemplateRepository) Fetch(pg *pagination.Pagination) (out []domain var stackTemplates []StackTemplate if pg == nil { - pg = pagination.NewDefaultPagination() + pg = pagination.NewPagination(nil) } - /* - filterFunc := CombinedGormFilter("stack_templates", pg.GetFilters(), pg.CombinedFilter) - db := filterFunc(r.db.Model(&StackTemplate{})) - db.Count(&pg.TotalRows) - - pg.TotalPages = int(math.Ceil(float64(pg.TotalRows) / float64(pg.Limit))) - orderQuery := fmt.Sprintf("%s %s", pg.SortColumn, pg.SortOrder) - res := db.Offset(pg.GetOffset()).Limit(pg.GetLimit()).Order("kube_type DESC,template_type ASC").Order(orderQuery).Find(&stackTemplates) - if res.Error != nil { - return nil, res.Error - } - - for _, stackTemplate := range stackTemplates { - out = append(out, reflectStackTemplate(stackTemplate)) - } - */ - - // paginator, res := filter.Scope(r.db.Order("kube_type DESC,template_type ASC"), pg.GetPaginationRequest(), &stackTemplates) _, res := pg.Fetch(r.db, &stackTemplates) if res.Error != nil { return nil, res.Error diff --git a/internal/repository/user.go b/internal/repository/user.go index c4c254c3..84120da9 100644 --- a/internal/repository/user.go +++ b/internal/repository/user.go @@ -1,8 +1,6 @@ package repository import ( - "fmt" - "math" "time" "github.com/google/uuid" @@ -147,6 +145,7 @@ func (r *UserRepository) NameFilter(name string) FilterFunc { func (r *UserRepository) List(filters ...FilterFunc) (*[]domain.User, error) { var users []User var res *gorm.DB + if filters == nil { res = r.db.Model(&User{}).Preload("Organization").Preload("Role").Find(&users) } else { @@ -161,6 +160,7 @@ func (r *UserRepository) List(filters ...FilterFunc) (*[]domain.User, error) { cFunc := combinedFilter(filters...) res = cFunc(r.db.Model(&User{}).Preload("Organization").Preload("Role")).Find(&users) } + if res.Error != nil { log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) return nil, res.Error @@ -181,16 +181,10 @@ func (r *UserRepository) ListWithPagination(pg *pagination.Pagination, organizat var users []User if pg == nil { - pg = pagination.NewDefaultPagination() + pg = pagination.NewPagination(nil) } - filterFunc := CombinedGormFilter("users", pg.GetFilters(), pg.CombinedFilter) - db := filterFunc(r.db.Model(&User{}).Where("organization_id = ?", organizationId)) - db.Count(&pg.TotalRows) - - pg.TotalPages = int(math.Ceil(float64(pg.TotalRows) / float64(pg.Limit))) - orderQuery := fmt.Sprintf("%s %s", pg.SortColumn, pg.SortOrder) - res := db.Preload("Organization").Preload("Role").Offset(pg.GetOffset()).Limit(pg.GetLimit()).Order(orderQuery).Find(&users) + _, res := pg.Fetch(r.db.Preload("Organization").Preload("Role").Model(&User{}).Where("organization_id = ?", organizationId), &users) if res.Error != nil { log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) return nil, res.Error diff --git a/internal/usecase/project.go b/internal/usecase/project.go index 0ad49670..a186e0ef 100644 --- a/internal/usecase/project.go +++ b/internal/usecase/project.go @@ -6,6 +6,7 @@ import ( "github.com/google/uuid" "github.com/openinfradev/tks-api/internal/keycloak" "github.com/openinfradev/tks-api/internal/kubernetes" + "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/repository" "github.com/openinfradev/tks-api/internal/serializer" argowf "github.com/openinfradev/tks-api/pkg/argo-client" @@ -24,7 +25,7 @@ const ( type IProjectUsecase interface { CreateProject(*domain.Project) (string, error) - GetProjects(organizationId string, userId string, onlyMyProject bool) ([]domain.ProjectResponse, error) + GetProjects(organizationId string, userId string, onlyMyProject bool, pg *pagination.Pagination) ([]domain.ProjectResponse, error) GetProject(organizationId string, projectId string) (*domain.Project, error) GetProjectWithLeader(organizationId string, projectId string) (*domain.Project, error) IsProjectNameExist(organizationId string, projectName string) (bool, error) @@ -34,13 +35,13 @@ type IProjectUsecase interface { AddProjectMember(pm *domain.ProjectMember) (string, error) GetProjectUser(projectUserId string) (*domain.ProjectUser, error) GetProjectMember(projectMemberId string) (*domain.ProjectMember, error) - GetProjectMembers(projectId string, query int) ([]domain.ProjectMember, error) + GetProjectMembers(projectId string, query int, pg *pagination.Pagination) ([]domain.ProjectMember, error) GetProjectMemberCount(projectMemberId string) (*domain.GetProjectMemberCountResponse, error) RemoveProjectMember(projectMemberId string) error UpdateProjectMemberRole(pm *domain.ProjectMember) error CreateProjectNamespace(organizationId string, pn *domain.ProjectNamespace) error IsProjectNamespaceExist(organizationId string, projectId string, stackId string, projectNamespace string) (bool, error) - GetProjectNamespaces(organizationId string, projectId string) ([]domain.ProjectNamespace, error) + GetProjectNamespaces(organizationId string, projectId string, pg *pagination.Pagination) ([]domain.ProjectNamespace, error) GetProjectNamespace(organizationId string, projectId string, projectNamespace string, stackId string) (*domain.ProjectNamespace, error) UpdateProjectNamespace(pn *domain.ProjectNamespace) error DeleteProjectNamespace(organizationId string, projectId string, projectNamespace string, stackId string) error @@ -91,20 +92,20 @@ func (u *ProjectUsecase) CreateProject(p *domain.Project) (string, error) { return projectId, nil } -func (u *ProjectUsecase) GetProjects(organizationId string, userId string, onlyMyProject bool) (pr []domain.ProjectResponse, err error) { +func (u *ProjectUsecase) GetProjects(organizationId string, userId string, onlyMyProject bool, pg *pagination.Pagination) (pr []domain.ProjectResponse, err error) { userUuid, err := uuid.Parse(userId) if err != nil { log.Error(err) return nil, errors.Wrap(err, "Failed to parse uuid to string") } if onlyMyProject == false { - pr, err = u.projectRepo.GetProjects(organizationId, userUuid) + pr, err = u.projectRepo.GetProjects(organizationId, userUuid, pg) if err != nil { log.Error(err) return nil, errors.Wrap(err, "Failed to get projects.") } } else { - pr, err = u.projectRepo.GetProjectsByUserId(organizationId, userUuid) + pr, err = u.projectRepo.GetProjectsByUserId(organizationId, userUuid, pg) if err != nil { log.Error(err) return nil, errors.Wrap(err, "Failed to get projects.") @@ -285,15 +286,15 @@ func (u *ProjectUsecase) GetProjectMember(projectMemberId string) (pm *domain.Pr return pm, nil } -func (u *ProjectUsecase) GetProjectMembers(projectId string, query int) (pms []domain.ProjectMember, err error) { +func (u *ProjectUsecase) GetProjectMembers(projectId string, query int, pg *pagination.Pagination) (pms []domain.ProjectMember, err error) { if query == ProjectLeader { - pms, err = u.projectRepo.GetProjectMembersByProjectIdAndRoleName(projectId, "project-leader") + pms, err = u.projectRepo.GetProjectMembersByProjectIdAndRoleName(projectId, "project-leader", pg) } else if query == ProjectMember { - pms, err = u.projectRepo.GetProjectMembersByProjectIdAndRoleName(projectId, "project-member") + pms, err = u.projectRepo.GetProjectMembersByProjectIdAndRoleName(projectId, "project-member", pg) } else if query == ProjectViewer { - pms, err = u.projectRepo.GetProjectMembersByProjectIdAndRoleName(projectId, "project-viewer") + pms, err = u.projectRepo.GetProjectMembersByProjectIdAndRoleName(projectId, "project-viewer", pg) } else { - pms, err = u.projectRepo.GetProjectMembersByProjectId(projectId) + pms, err = u.projectRepo.GetProjectMembersByProjectId(projectId, pg) } if err != nil { log.Error(err) @@ -352,8 +353,8 @@ func (u *ProjectUsecase) IsProjectNamespaceExist(organizationId string, projectI return exist, nil } -func (u *ProjectUsecase) GetProjectNamespaces(organizationId string, projectId string) ([]domain.ProjectNamespace, error) { - pns, err := u.projectRepo.GetProjectNamespaces(organizationId, projectId) +func (u *ProjectUsecase) GetProjectNamespaces(organizationId string, projectId string, pg *pagination.Pagination) ([]domain.ProjectNamespace, error) { + pns, err := u.projectRepo.GetProjectNamespaces(organizationId, projectId, pg) if err != nil { log.Error(err) return nil, errors.Wrap(err, "Failed to retrieve project namespaces.") @@ -404,7 +405,7 @@ func (u *ProjectUsecase) GetAppCount(organizationId string, projectId string, na } func (u *ProjectUsecase) EnsureRequiredSetupForCluster(organizationId string, projectId string, stackId string) error { - pns, err := u.projectRepo.GetProjectNamespaces(organizationId, projectId) + pns, err := u.projectRepo.GetProjectNamespaces(organizationId, projectId, nil) if err != nil { log.Error(err) return errors.Wrap(err, "Failed to create project namespace.") @@ -433,7 +434,7 @@ func (u *ProjectUsecase) EnsureRequiredSetupForCluster(organizationId string, pr return errors.Wrap(err, "Failed to create project namespace.") } - projectMembers, err := u.GetProjectMembers(projectId, ProjectAll) + projectMembers, err := u.GetProjectMembers(projectId, ProjectAll, nil) if err != nil { log.Error(err) return errors.Wrap(err, "Failed to create project namespace.") @@ -449,7 +450,7 @@ func (u *ProjectUsecase) EnsureRequiredSetupForCluster(organizationId string, pr return nil } func (u *ProjectUsecase) MayRemoveRequiredSetupForCluster(organizationId string, projectId string, stackId string) error { - pns, err := u.projectRepo.GetProjectNamespaces(organizationId, projectId) + pns, err := u.projectRepo.GetProjectNamespaces(organizationId, projectId, nil) if err != nil { log.Error(err) return errors.Wrap(err, "Failed to create project namespace.") @@ -471,7 +472,7 @@ func (u *ProjectUsecase) MayRemoveRequiredSetupForCluster(organizationId string, return errors.Wrap(err, "Failed to create project namespace.") } - projectMembers, err := u.GetProjectMembers(projectId, ProjectAll) + projectMembers, err := u.GetProjectMembers(projectId, ProjectAll, nil) if err != nil { log.Error(err) return errors.Wrap(err, "Failed to create project namespace.") @@ -646,7 +647,7 @@ func (u *ProjectUsecase) unassignKeycloakClientRoleToMember(organizationId strin } func (u *ProjectUsecase) GetProjectKubeconfig(organizationId string, projectId string) (string, error) { - projectNamespaces, err := u.projectRepo.GetProjectNamespaces(organizationId, projectId) + projectNamespaces, err := u.projectRepo.GetProjectNamespaces(organizationId, projectId, nil) if err != nil { log.Error(err) return "", errors.Wrap(err, "Failed to retrieve project namespaces.") diff --git a/pkg/domain/project.go b/pkg/domain/project.go index 9660622e..bfb13715 100644 --- a/pkg/domain/project.go +++ b/pkg/domain/project.go @@ -58,7 +58,8 @@ type ProjectResponse struct { } type GetProjectsResponse struct { - Projects []ProjectResponse `json:"projects"` + Projects []ProjectResponse `json:"projects"` + Pagination PaginationResponse `json:"pagination"` } type ProjectDetailResponse struct { @@ -192,6 +193,7 @@ type GetProjectMemberResponse struct { type GetProjectMembersResponse struct { ProjectMembers []ProjectMemberResponse `json:"projectMembers"` + Pagination PaginationResponse `json:"pagination"` } type GetProjectMemberCountResponse struct {