Skip to content

Commit

Permalink
feature. add API(/primary-cluster) to organization
Browse files Browse the repository at this point in the history
  • Loading branch information
ktkfree committed Mar 30, 2023
1 parent 68b4975 commit ee23128
Show file tree
Hide file tree
Showing 8 changed files with 198 additions and 27 deletions.
40 changes: 39 additions & 1 deletion api/swagger/docs.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Code generated by swaggo/swag. DO NOT EDIT
// Package swagger GENERATED BY SWAG; DO NOT EDIT
// This file was generated by swaggo/swag
package swagger

import "github.com/swaggo/swag"
Expand Down Expand Up @@ -1015,6 +1016,40 @@ const docTemplate = `{
}
}
}
},
"/organizations/{organizationId}/primary-cluster": {
"put": {
"security": [
{
"JWT": []
}
],
"description": "Update primary cluster",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Organizations"
],
"summary": "Update primary cluster",
"parameters": [
{
"type": "string",
"description": "organizationId",
"name": "organizationId",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK"
}
}
}
}
},
"definitions": {
Expand Down Expand Up @@ -1362,6 +1397,9 @@ const docTemplate = `{
"phone": {
"type": "string"
},
"primaryClusterId": {
"type": "string"
},
"status": {
"type": "string"
},
Expand Down
37 changes: 37 additions & 0 deletions api/swagger/swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -1009,6 +1009,40 @@
}
}
}
},
"/organizations/{organizationId}/primary-cluster": {
"put": {
"security": [
{
"JWT": []
}
],
"description": "Update primary cluster",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Organizations"
],
"summary": "Update primary cluster",
"parameters": [
{
"type": "string",
"description": "organizationId",
"name": "organizationId",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK"
}
}
}
}
},
"definitions": {
Expand Down Expand Up @@ -1356,6 +1390,9 @@
"phone": {
"type": "string"
},
"primaryClusterId": {
"type": "string"
},
"status": {
"type": "string"
},
Expand Down
23 changes: 23 additions & 0 deletions api/swagger/swagger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,8 @@ definitions:
type: string
phone:
type: string
primaryClusterId:
type: string
status:
type: string
statusDescription:
Expand Down Expand Up @@ -932,6 +934,27 @@ paths:
summary: Update organization detail
tags:
- Organizations
/organizations/{organizationId}/primary-cluster:
put:
consumes:
- application/json
description: Update primary cluster
parameters:
- description: organizationId
in: path
name: organizationId
required: true
type: string
produces:
- application/json
responses:
"200":
description: OK
security:
- JWT: []
summary: Update primary cluster
tags:
- Organizations
securityDefinitions:
JWT:
in: header
Expand Down
39 changes: 38 additions & 1 deletion internal/delivery/http/organization.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package http

import (
"fmt"
"github.com/openinfradev/tks-api/pkg/httpErrors"
"net/http"

"github.com/openinfradev/tks-api/pkg/httpErrors"

"github.com/gorilla/mux"
"github.com/openinfradev/tks-api/internal/auth/request"
"github.com/openinfradev/tks-api/internal/usecase"
Expand Down Expand Up @@ -219,3 +220,39 @@ func (h *OrganizationHandler) UpdateOrganization(w http.ResponseWriter, r *http.

ResponseJSON(w, http.StatusOK, nil)
}

// UpdatePrimaryCluster godoc
// @Tags Organizations
// @Summary Update primary cluster
// @Description Update primary cluster
// @Accept json
// @Produce json
// @Param organizationId path string true "organizationId"
// @Success 200 {object} nil
// @Router /organizations/{organizationId}/primary-cluster [put]
// @Security JWT
func (h *OrganizationHandler) UpdatePrimaryCluster(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
organizationId, ok := vars["organizationId"]
if !ok {
ErrorJSON(w, httpErrors.NewBadRequestError(fmt.Errorf("invalid organizationId")))
return
}

input := domain.UpdatePrimaryClusterRequest{}
err := UnmarshalRequestInput(r, &input)
if err != nil {
ErrorJSON(w, httpErrors.NewBadRequestError(err))
return
}

err = h.usecase.UpdatePrimaryClusterId(organizationId, input.PrimaryClusterId)
if err != nil {
ErrorJSON(w, err)
return
}

log.Info(input)

ResponseJSON(w, http.StatusOK, nil)
}
41 changes: 22 additions & 19 deletions internal/repository/organization.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,15 @@ func NewOrganizationRepository(db *gorm.DB) IOrganizationRepository {
type Organization struct {
gorm.Model

ID string `gorm:"primarykey;type:varchar(36);not null"`
Name string
Description string
Phone string
WorkflowId string
Status domain.OrganizationStatus
StatusDesc string
Creator uuid.UUID
ID string `gorm:"primarykey;type:varchar(36);not null"`
Name string
Description string
Phone string
WorkflowId string
Status domain.OrganizationStatus
StatusDesc string
Creator uuid.UUID
PrimaryClusterId string // allow null
}

//func (c *Organization) BeforeCreate(tx *gorm.DB) (err error) {
Expand Down Expand Up @@ -99,8 +100,9 @@ func (r *OrganizationRepository) Update(organizationId string, in domain.UpdateO
res := r.db.Model(&Organization{}).
Where("id = ?", organizationId).
Updates(Organization{
Description: in.Description,
Phone: in.Phone,
Description: in.Description,
Phone: in.Phone,
PrimaryClusterId: in.PrimaryClusterId,
})
if res.Error != nil {
log.Error("error is :%s(%T)", res.Error.Error(), res.Error)
Expand Down Expand Up @@ -140,19 +142,20 @@ func (r *OrganizationRepository) InitWorkflow(organizationId string, workflowId
//if res.Error != nil || res.RowsAffected == 0 {
// return fmt.Errorf("nothing updated in organization with id %s", organizationId)
//}

return nil
}

func (r *OrganizationRepository) reflect(organization Organization) domain.Organization {
return domain.Organization{
ID: organization.ID,
Name: organization.Name,
Description: organization.Description,
Phone: organization.Phone,
Status: organization.Status.String(),
Creator: organization.Creator.String(),
CreatedAt: organization.CreatedAt,
UpdatedAt: organization.UpdatedAt,
ID: organization.ID,
Name: organization.Name,
Description: organization.Description,
Phone: organization.Phone,
PrimaryClusterId: organization.PrimaryClusterId,
Status: organization.Status.String(),
Creator: organization.Creator.String(),
CreatedAt: organization.CreatedAt,
UpdatedAt: organization.UpdatedAt,
}
}
8 changes: 4 additions & 4 deletions internal/route/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,7 @@ func SetupRouter(db *gorm.DB, argoClient argowf.ArgoClient, asset http.Handler,
r.Handle(API_PREFIX+API_VERSION+"/users", authMiddleware(http.HandlerFunc(userHandler.List), kc)).Methods(http.MethodGet)
r.Handle(API_PREFIX+API_VERSION+"/users/{userId}", authMiddleware(http.HandlerFunc(userHandler.Get), kc)).Methods(http.MethodGet)
r.Handle(API_PREFIX+API_VERSION+"/users/{userId}", authMiddleware(http.HandlerFunc(userHandler.Delete), kc)).Methods(http.MethodDelete)
r.Handle(API_PREFIX+API_VERSION+"/users/{userId}", authMiddleware(http.HandlerFunc(userHandler.Update), kc)).Methods(http.MethodPut)
r.Handle(API_PREFIX+API_VERSION+"/users/{userId}/password", authMiddleware(http.HandlerFunc(userHandler.UpdatePassword), kc)).Methods(http.MethodPut)
r.Handle(API_PREFIX+API_VERSION+"/users/{userId}/password", authMiddleware(http.HandlerFunc(userHandler.UpdatePassword), kc)).Methods(http.MethodPatch)
r.Handle(API_PREFIX+API_VERSION+"/users/{userId}", authMiddleware(http.HandlerFunc(userHandler.CheckId), kc)).Methods(http.MethodPost)

organizationHandler := delivery.NewOrganizationHandler(usecase.NewOrganizationUsecase(repository.NewOrganizationRepository(db),
Expand All @@ -136,6 +135,7 @@ func SetupRouter(db *gorm.DB, argoClient argowf.ArgoClient, asset http.Handler,
r.Handle(API_PREFIX+API_VERSION+"/organizations/{organizationId}", authMiddleware(http.HandlerFunc(organizationHandler.GetOrganization), kc)).Methods(http.MethodGet)
r.Handle(API_PREFIX+API_VERSION+"/organizations/{organizationId}", authMiddleware(http.HandlerFunc(organizationHandler.DeleteOrganization), kc)).Methods(http.MethodDelete)
r.Handle(API_PREFIX+API_VERSION+"/organizations/{organizationId}", authMiddleware(http.HandlerFunc(organizationHandler.UpdateOrganization), kc)).Methods(http.MethodPut)
r.Handle(API_PREFIX+API_VERSION+"/organizations/{organizationId}/primary-cluster", authMiddleware(http.HandlerFunc(organizationHandler.UpdatePrimaryCluster), kc)).Methods(http.MethodPatch)

clusterHandler := delivery.NewClusterHandler(usecase.NewClusterUsecase(
repository.NewClusterRepository(db),
Expand Down Expand Up @@ -280,7 +280,7 @@ func authMiddleware(next http.Handler, kc keycloak.IKeycloak) http.Handler {
jwtToken, mapClaims, err := kc.ParseAccessToken(token, organization)
if err != nil {
log.Error("failed to parse access token: ", err)
w.WriteHeader(http.StatusUnauthorized)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
Expand All @@ -295,7 +295,7 @@ func authMiddleware(next http.Handler, kc keycloak.IKeycloak) http.Handler {
slice := strings.Split(role.(string), "@")
if len(slice) != 2 {
log.Error("invalid role format: ", role)
w.WriteHeader(http.StatusBadRequest)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("invalid role format: %s", role)))
return
}
Expand Down
26 changes: 26 additions & 0 deletions internal/usecase/organization.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package usecase
import (
"context"
"fmt"

"github.com/openinfradev/tks-api/internal/auth/request"
"github.com/openinfradev/tks-api/internal/helper"
"github.com/openinfradev/tks-api/internal/keycloak"
Expand All @@ -21,6 +22,7 @@ type IOrganizationUsecase interface {
Fetch() (*[]domain.Organization, error)
Get(organizationId string) (domain.Organization, error)
Update(organizationId string, in domain.UpdateOrganizationRequest) (err error)
UpdatePrimaryClusterId(organizationId string, clusterId string) (err error)
Delete(organizationId string, accessToken string) error
}

Expand Down Expand Up @@ -129,3 +131,27 @@ func (u *OrganizationUsecase) Update(organizationId string, in domain.UpdateOrga
}
return nil
}

func (u *OrganizationUsecase) UpdatePrimaryClusterId(organizationId string, clusterId string) (err error) {
if !helper.ValidateClusterId(clusterId) {
return httpErrors.NewBadRequestError(fmt.Errorf("Invalid clusterId"))
}

organization, err := u.Get(organizationId)
if err != nil {
return httpErrors.NewNotFoundError(err)
}

// [TODO] need refactoring about reflect
in := domain.UpdateOrganizationRequest{
Description: organization.Description,
Phone: organization.Phone,
PrimaryClusterId: clusterId,
}

_, err = u.repo.Update(organizationId, in)
if err != nil {
return err
}
return nil
}
11 changes: 9 additions & 2 deletions pkg/domain/organization.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ type Organization = struct {
Name string `json:"name"`
Description string `json:"description"`
Phone string `json:"phone"`
PrimaryClusterId string `json:"primaryClusterId,omitempty"`
Status string `json:"status"`
StatusDescription string `json:"statusDescription"`
Creator string `json:"creator"`
Expand Down Expand Up @@ -72,8 +73,9 @@ func (r *CreateOrganizationRequest) ToOrganization() *Organization {
}

type UpdateOrganizationRequest struct {
Description string `json:"description"`
Phone string `json:"phone"`
Description string `json:"description"`
Phone string `json:"phone"`
PrimaryClusterId string `json:"primaryClusterId,omitempty"`
}

func (r *UpdateOrganizationRequest) ToOrganization() *Organization {
Expand All @@ -82,10 +84,15 @@ func (r *UpdateOrganizationRequest) ToOrganization() *Organization {
Name: "",
Description: r.Description,
Phone: r.Phone,
PrimaryClusterId: r.PrimaryClusterId,
Status: "",
StatusDescription: "",
Creator: "",
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
}
}

type UpdatePrimaryClusterRequest struct {
PrimaryClusterId string `json:"primaryClusterId,omitempty"`
}

0 comments on commit ee23128

Please sign in to comment.