Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(api): implement project webhook service (#4995)

h3n4l6334ebad980e
diff --git a/backend/api/v1/project_service.go b/backend/api/v1/project_service.go
index 8e34905c7e..1cf2938761 100644
--- a/backend/api/v1/project_service.go
+++ b/backend/api/v1/project_service.go
@@ -4,12 +4,16 @@ import (
"context"
"fmt"
"strings"
+ "time"
+ "github.com/gosimple/slug"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
+ webhookPlugin "github.com/bytebase/bytebase/backend/plugin/webhook"
+
"github.com/bytebase/bytebase/backend/common"
api "github.com/bytebase/bytebase/backend/legacyapi"
"github.com/bytebase/bytebase/backend/store"
@@ -330,6 +334,299 @@ func (s *ProjectService) UpdateDeploymentConfig(ctx context.Context, request *v1
return convertToDeploymentConfig(project.ResourceID, deploymentConfig), nil
}
+// AddWebhook adds a webhook to a given project.
+func (s *ProjectService) AddWebhook(ctx context.Context, request *v1pb.AddWebhookRequest) (*v1pb.Project, error) {
+ projectID, err := getProjectID(request.Project)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, err.Error())
+ }
+ project, err := s.store.GetProjectV2(ctx, &store.FindProjectMessage{
+ ResourceID: &projectID,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ if project == nil {
+ return nil, status.Errorf(codes.NotFound, "project %q not found", request.Project)
+ }
+ if project.Deleted {
+ return nil, status.Errorf(codes.InvalidArgument, "project %q has been deleted", request.Project)
+ }
+
+ create, err := convertToStoreProjectWebhookMessage(request.Webhook)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, err.Error())
+ }
+
+ if _, err := s.store.CreateProjectWebhookV2(ctx, ctx.Value(common.PrincipalIDContextKey).(int), project.UID, project.ResourceID, create); err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+
+ project, err = s.store.GetProjectV2(ctx, &store.FindProjectMessage{
+ ResourceID: &projectID,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ return convertToProject(project), nil
+}
+
+// UpdateWebhook updates a webhook.
+func (s *ProjectService) UpdateWebhook(ctx context.Context, request *v1pb.UpdateWebhookRequest) (*v1pb.Project, error) {
+ projectID, err := getProjectID(request.Project)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, err.Error())
+ }
+ project, err := s.store.GetProjectV2(ctx, &store.FindProjectMessage{
+ ResourceID: &projectID,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ if project == nil {
+ return nil, status.Errorf(codes.NotFound, "project %q not found", request.Project)
+ }
+ if project.Deleted {
+ return nil, status.Errorf(codes.InvalidArgument, "project %q has been deleted", request.Project)
+ }
+
+ webhook, err := s.store.GetProjectWebhookV2(ctx, &store.FindProjectWebhookMessage{
+ ProjectID: &project.UID,
+ URL: &request.Webhook.Url,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ if webhook == nil {
+ return nil, status.Errorf(codes.NotFound, "webhook %q not found", request.Webhook.Url)
+ }
+
+ update := &store.UpdateProjectWebhookMessage{}
+ for _, path := range request.UpdateMask.Paths {
+ switch path {
+ case "webhook.type":
+ return nil, status.Errorf(codes.InvalidArgument, "type cannot be updated")
+ case "webhook.title":
+ update.Title = &request.Webhook.Title
+ case "webhook.url":
+ update.URL = &request.Webhook.Url
+ case "webhook.notification_type":
+ types, err := convertToActivityTypeStrings(request.Webhook.NotificationTypes)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, err.Error())
+ }
+ update.ActivityList = types
+ default:
+ return nil, status.Errorf(codes.InvalidArgument, "invalid field %q", path)
+ }
+ }
+
+ if _, err := s.store.UpdateProjectWebhookV2(ctx, ctx.Value(common.PrincipalIDContextKey).(int), project.UID, project.ResourceID, webhook.ID, update); err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+
+ project, err = s.store.GetProjectV2(ctx, &store.FindProjectMessage{
+ ResourceID: &projectID,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ return convertToProject(project), nil
+}
+
+// RemoveWebhook removes a webhook from a given project.
+func (s *ProjectService) RemoveWebhook(ctx context.Context, request *v1pb.RemoveWebhookRequest) (*v1pb.Project, error) {
+ projectID, err := getProjectID(request.Project)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, err.Error())
+ }
+ project, err := s.store.GetProjectV2(ctx, &store.FindProjectMessage{
+ ResourceID: &projectID,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ if project == nil {
+ return nil, status.Errorf(codes.NotFound, "project %q not found", request.Project)
+ }
+ if project.Deleted {
+ return nil, status.Errorf(codes.InvalidArgument, "project %q has been deleted", request.Project)
+ }
+
+ webhook, err := s.store.GetProjectWebhookV2(ctx, &store.FindProjectWebhookMessage{
+ ProjectID: &project.UID,
+ URL: &request.Webhook.Url,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ if webhook == nil {
+ return nil, status.Errorf(codes.NotFound, "webhook %q not found", request.Webhook.Url)
+ }
+
+ if err := s.store.DeleteProjectWebhookV2(ctx, project.UID, project.ResourceID, webhook.ID); err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+
+ project, err = s.store.GetProjectV2(ctx, &store.FindProjectMessage{
+ ResourceID: &projectID,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ return convertToProject(project), nil
+}
+
+// TestWebhook tests a webhook.
+func (s *ProjectService) TestWebhook(ctx context.Context, request *v1pb.TestWebhookRequest) (*v1pb.TestWebhookResponse, error) {
+ projectID, err := getProjectID(request.Project)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, err.Error())
+ }
+ project, err := s.store.GetProjectV2(ctx, &store.FindProjectMessage{
+ ResourceID: &projectID,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ if project == nil {
+ return nil, status.Errorf(codes.NotFound, "project %q not found", request.Project)
+ }
+ if project.Deleted {
+ return nil, status.Errorf(codes.InvalidArgument, "project %q has been deleted", request.Project)
+ }
+
+ webhook, err := s.store.GetProjectWebhookV2(ctx, &store.FindProjectWebhookMessage{
+ ProjectID: &project.UID,
+ URL: &request.Webhook.Url,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ if webhook == nil {
+ return nil, status.Errorf(codes.NotFound, "webhook %q not found", request.Webhook.Url)
+ }
+
+ setting, err := s.store.GetWorkspaceGeneralSetting(ctx)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+
+ err = webhookPlugin.Post(
+ webhook.Type,
+ webhookPlugin.Context{
+ URL: webhook.URL,
+ Level: webhookPlugin.WebhookInfo,
+ ActivityType: string(api.ActivityIssueCreate),
+ Title: fmt.Sprintf("Test webhook %q", webhook.Title),
+ Description: "This is a test",
+ Link: fmt.Sprintf("%s/project/%s/webhook/%s", setting.ExternalUrl, fmt.Sprintf("%s-%d", slug.Make(project.Title), project.UID), fmt.Sprintf("%s-%d", slug.Make(webhook.Title), webhook.ID)),
+ CreatorID: api.SystemBotID,
+ CreatorName: "Bytebase",
+ CreatorEmail: "[email protected]",
+ CreatedTs: time.Now().Unix(),
+ Project: &webhookPlugin.Project{Name: project.Title},
+ },
+ )
+
+ return &v1pb.TestWebhookResponse{Error: err.Error()}, nil
+}
+
+func convertToStoreProjectWebhookMessage(webhook *v1pb.Webhook) (*store.ProjectWebhookMessage, error) {
+ tp, err := convertToAPIWebhookTypeString(webhook.Type)
+ if err != nil {
+ return nil, err
+ }
+ activityTypes, err := convertToActivityTypeStrings(webhook.NotificationTypes)
+ if err != nil {
+ return nil, err
+ }
+ return &store.ProjectWebhookMessage{
+ Type: tp,
+ URL: webhook.Url,
+ Title: webhook.Title,
+ ActivityList: activityTypes,
+ }, nil
+}
+
+func convertToActivityTypeStrings(types []v1pb.Activity_Type) ([]string, error) {
+ var result []string
+
+ for _, tp := range types {
+ switch tp {
+ case v1pb.Activity_TYPE_UNSPECIFIED:
+ return nil, common.Errorf(common.Invalid, "activity type must not be unspecified")
+ case v1pb.Activity_TYPE_ISSUE_CREATE:
+ result = append(result, string(api.ActivityIssueCreate))
+ case v1pb.Activity_TYPE_ISSUE_COMMENT_CREATE:
+ result = append(result, string(api.ActivityIssueCommentCreate))
+ case v1pb.Activity_TYPE_ISSUE_FIELD_UPDATE:
+ result = append(result, string(api.ActivityIssueFieldUpdate))
+ case v1pb.Activity_TYPE_ISSUE_STATUS_UPDATE:
+ result = append(result, string(api.ActivityIssueStatusUpdate))
+ case v1pb.Activity_TYPE_ISSUE_PIPELINE_STAGE_STATUS_UPDATE:
+ result = append(result, string(api.ActivityPipelineStageStatusUpdate))
+ case v1pb.Activity_TYPE_ISSUE_PIPELINE_TASK_STATUS_UPDATE:
+ result = append(result, string(api.ActivityPipelineTaskStatusUpdate))
+ case v1pb.Activity_TYPE_ISSUE_PIPELINE_TASK_FILE_COMMIT:
+ result = append(result, string(api.ActivityPipelineTaskFileCommit))
+ case v1pb.Activity_TYPE_ISSUE_PIPELINE_TASK_STATEMENT_UPDATE:
+ result = append(result, string(api.ActivityPipelineTaskStatementUpdate))
+ case v1pb.Activity_TYPE_ISSUE_PIPELINE_TASK_EARLIEST_ALLOWED_TIME_UPDATE:
+ result = append(result, string(api.ActivityPipelineTaskEarliestAllowedTimeUpdate))
+ case v1pb.Activity_TYPE_MEMBER_CREATE:
+ result = append(result, string(api.ActivityMemberCreate))
+ case v1pb.Activity_TYPE_MEMBER_ROLE_UPDATE:
+ result = append(result, string(api.ActivityMemberRoleUpdate))
+ case v1pb.Activity_TYPE_MEMBER_ACTIVATE:
+ result = append(result, string(api.ActivityMemberActivate))
+ case v1pb.Activity_TYPE_MEMBER_DEACTIVATE:
+ result = append(result, string(api.ActivityMemberDeactivate))
+ case v1pb.Activity_TYPE_PROJECT_REPOSITORY_PUSH:
+ result = append(result, string(api.ActivityProjectRepositoryPush))
+ case v1pb.Activity_TYPE_PROJECT_DATABASE_TRANSFER:
+ result = append(result, string(api.ActivityProjectDatabaseTransfer))
+ case v1pb.Activity_TYPE_PROJECT_MEMBER_CREATE:
+ result = append(result, string(api.ActivityProjectMemberCreate))
+ case v1pb.Activity_TYPE_PROJECT_MEMBER_DELETE:
+ result = append(result, string(api.ActivityProjectMemberDelete))
+ case v1pb.Activity_TYPE_PROJECT_MEMBER_ROLE_UPDATE:
+ result = append(result, string(api.ActivityProjectMemberRoleUpdate))
+ case v1pb.Activity_TYPE_SQL_EDITOR_QUERY:
+ result = append(result, string(api.ActivitySQLEditorQuery))
+ case v1pb.Activity_TYPE_DATABASE_RECOVERY_PITR_DONE:
+ result = append(result, string(api.ActivityDatabaseRecoveryPITRDone))
+ default:
+ return nil, common.Errorf(common.Invalid, "unsupported activity type: %v", tp)
+ }
+ }
+ return result, nil
+}
+
+func convertToAPIWebhookTypeString(tp v1pb.Webhook_Type) (string, error) {
+ switch tp {
+ case v1pb.Webhook_TYPE_UNSPECIFIED:
+ return "", common.Errorf(common.Invalid, "webhook type must not be unspecified")
+ // TODO(zp): find a better way to place the "bb.plugin.webhook.*".
+ case v1pb.Webhook_TYPE_SLACK:
+ return "bb.plugin.webhook.slack", nil
+ case v1pb.Webhook_TYPE_DISCORD:
+ return "bb.plugin.webhook.discord", nil
+ case v1pb.Webhook_TYPE_TEAMS:
+ return "bb.plugin.webhook.teams", nil
+ case v1pb.Webhook_TYPE_DINGTALK:
+ return "bb.plugin.webhook.dingtalk", nil
+ case v1pb.Webhook_TYPE_FEISHU:
+ return "bb.plugin.webhook.feishu", nil
+ case v1pb.Webhook_TYPE_WECOM:
+ return "bb.plugin.webhook.wecom", nil
+ case v1pb.Webhook_TYPE_CUSTOM:
+ return "bb.plugin.webhook.custom", nil
+ default:
+ return "", common.Errorf(common.Invalid, "webhook type %q is not supported", tp)
+ }
+}
+
func validateAndConvertToStoreDeploymentSchedule(deployment *v1pb.DeploymentConfig) (*store.DeploymentConfigMessage, error) {
if deployment.Schedule == nil {
return nil, common.Errorf(common.Invalid, "schedule must not be empty")
diff --git a/backend/component/activity/manager.go b/backend/component/activity/manager.go
index 0aadcf4235..620e0a2126 100644
--- a/backend/component/activity/manager.go
+++ b/backend/component/activity/manager.go
@@ -74,7 +74,7 @@ func (m *Manager) BatchCreateTaskStatusUpdateApprovalActivity(ctx context.Contex
anyActivity := activityList[0]
activityType := api.ActivityPipelineTaskStatusUpdate
- webhookList, err := m.store.FindProjectWebhook(ctx, &api.ProjectWebhookFind{
+ webhookList, err := m.store.FindProjectWebhookV2(ctx, &store.FindProjectWebhookMessage{
ProjectID: &issue.Project.UID,
ActivityType: &activityType,
})
@@ -138,11 +138,10 @@ func (m *Manager) CreateActivity(ctx context.Context, create *api.ActivityCreate
}
}
- hookFind := &api.ProjectWebhookFind{
+ webhookList, err := m.store.FindProjectWebhookV2(ctx, &store.FindProjectWebhookMessage{
ProjectID: &meta.Issue.Project.UID,
ActivityType: &create.Type,
- }
- webhookList, err := m.store.FindProjectWebhook(ctx, hookFind)
+ })
if err != nil {
return nil, errors.Wrapf(err, "failed to find project webhook after changing the issue status: %v", meta.Issue.Title)
}
@@ -171,7 +170,7 @@ func (m *Manager) CreateActivity(ctx context.Context, create *api.ActivityCreate
return activity, nil
}
-func postWebhookList(webhookCtx webhook.Context, webhookList []*api.ProjectWebhook) {
+func postWebhookList(webhookCtx webhook.Context, webhookList []*store.ProjectWebhookMessage) {
for _, hook := range webhookList {
webhookCtx.URL = hook.URL
webhookCtx.CreatedTs = time.Now().Unix()
@@ -181,7 +180,7 @@ func postWebhookList(webhookCtx webhook.Context, webhookList []*api.ProjectWebho
// The external webhook endpoint might be invalid which is out of our code control, so we just emit a warning
log.Warn("Failed to post webhook event on activity",
zap.String("webhook type", hook.Type),
- zap.String("webhook name", hook.Name),
+ zap.String("webhook name", hook.Title),
zap.String("activity type", webhookCtx.ActivityType),
zap.String("title", webhookCtx.Title),
zap.Error(err))
diff --git a/backend/legacyapi/project_webhook.go b/backend/legacyapi/project_webhook.go
index ba9fbdd570..52d95cb52f 100644
--- a/backend/legacyapi/project_webhook.go
+++ b/backend/legacyapi/project_webhook.go
@@ -1,9 +1,5 @@
package api
-import (
- "encoding/json"
-)
-
// ProjectWebhook is the API message for project webhooks.
type ProjectWebhook struct {
ID int `jsonapi:"primary,projectWebhookMember"`
@@ -35,23 +31,6 @@ type ProjectWebhookCreate struct {
ActivityList []string `jsonapi:"attr,activityList"`
}
-// ProjectWebhookFind is the API message for finding project webhooks.
-type ProjectWebhookFind struct {
- ID *int
-
- // Related fields
- ProjectID *int
- ActivityType *ActivityType
-}
-
-func (find *ProjectWebhookFind) String() string {
- str, err := json.Marshal(*find)
- if err != nil {
- return err.Error()
- }
- return string(str)
-}
-
// ProjectWebhookPatch is the API message for patching a project webhook.
type ProjectWebhookPatch struct {
ID int
@@ -66,15 +45,6 @@ type ProjectWebhookPatch struct {
ActivityList *string `jsonapi:"attr,activityList"`
}
-// ProjectWebhookDelete is the API message for deleting a project webhook.
-type ProjectWebhookDelete struct {
- ID int
-
- // Standard fields
- // Value is assigned from the jwt subject field passed by the client.
- DeleterID int
-}
-
// ProjectWebhookTestResult is the test result of a project webhook.
type ProjectWebhookTestResult struct {
Error string `jsonapi:"attr,error"`
diff --git a/backend/legacyapi/slug.go b/backend/legacyapi/slug.go
index 5bf6e0c1b8..f0f4a581b7 100644
--- a/backend/legacyapi/slug.go
+++ b/backend/legacyapi/slug.go
@@ -22,6 +22,6 @@ func EnvSlug(env *Environment) string {
}
// ProjectWebhookSlug is the slug formatter for project webhooks.
-func ProjectWebhookSlug(projectWebhook *ProjectWebhook) string {
- return fmt.Sprintf("%s-%d", slug.Make(projectWebhook.Name), projectWebhook.ID)
+func ProjectWebhookSlug(name string, id int) string {
+ return fmt.Sprintf("%s-%d", slug.Make(name), id)
}
diff --git a/backend/server/project_webhook.go b/backend/server/project_webhook.go
index 3aad505c57..6e22a3d083 100644
--- a/backend/server/project_webhook.go
+++ b/backend/server/project_webhook.go
@@ -4,6 +4,7 @@ import (
"fmt"
"net/http"
"strconv"
+ "strings"
"time"
"github.com/google/jsonapi"
@@ -23,17 +24,20 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectID"))).SetInternal(err)
}
-
- find := &api.ProjectWebhookFind{
+ webhookList, err := s.store.FindProjectWebhookV2(ctx, &store.FindProjectWebhookMessage{
ProjectID: &projectID,
- }
- webhookList, err := s.store.FindProjectWebhook(ctx, find)
+ })
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch webhook list for project ID: %d", projectID)).SetInternal(err)
}
+ var apiWebhookList []*api.ProjectWebhook
+ for _, webhook := range webhookList {
+ apiWebhookList = append(apiWebhookList, webhook.ToAPIProjectWebhook())
+ }
+
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, webhookList); err != nil {
+ if err := jsonapi.MarshalPayload(c.Response().Writer, apiWebhookList); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal project webhook response: %v", projectID)).SetInternal(err)
}
return nil
@@ -53,8 +57,15 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
if err := jsonapi.UnmarshalPayload(c.Request().Body, hookCreate); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformed create project webhook request").SetInternal(err)
}
+ project, err := s.store.GetProjectByID(ctx, projectID)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project ID: %v", projectID)).SetInternal(err)
+ }
+ if project == nil {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project ID not found: %v", projectID))
+ }
- webhook, err := s.store.CreateProjectWebhook(ctx, hookCreate)
+ webhook, err := s.store.CreateProjectWebhookV2(ctx, c.Get(getPrincipalIDContextKey()).(int), projectID, project.ResourceID, &store.ProjectWebhookMessage{})
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Webhook url already exists in the project: %s", hookCreate.URL))
@@ -63,7 +74,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, webhook); err != nil {
+ if err := jsonapi.MarshalPayload(c.Response().Writer, webhook.ToAPIProjectWebhook()); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal create project webhook response").SetInternal(err)
}
return nil
@@ -81,7 +92,9 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project webhook ID is not a number: %s", c.Param("webhookID"))).SetInternal(err)
}
- webhook, err := s.store.GetProjectWebhookByID(ctx, id)
+ webhook, err := s.store.GetProjectWebhookV2(ctx, &store.FindProjectWebhookMessage{
+ ID: &id,
+ })
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project webhook ID: %v", id)).SetInternal(err)
}
@@ -90,7 +103,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, webhook); err != nil {
+ if err := jsonapi.MarshalPayload(c.Response().Writer, webhook.ToAPIProjectWebhook()); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal project webhook ID response: %v", id)).SetInternal(err)
}
return nil
@@ -98,7 +111,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
g.PATCH("/project/:projectID/webhook/:webhookID", func(c echo.Context) error {
ctx := c.Request().Context()
- _, err := strconv.Atoi(c.Param("projectID"))
+ projectID, err := strconv.Atoi(c.Param("projectID"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectID"))).SetInternal(err)
}
@@ -108,6 +121,14 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project webhook ID is not a number: %s", c.Param("webhookID"))).SetInternal(err)
}
+ project, err := s.store.GetProjectByID(ctx, projectID)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project ID: %v", projectID)).SetInternal(err)
+ }
+ if project == nil {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project ID not found: %v", projectID))
+ }
+
hookPatch := &api.ProjectWebhookPatch{
ID: id,
UpdaterID: c.Get(getPrincipalIDContextKey()).(int),
@@ -115,8 +136,16 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
if err := jsonapi.UnmarshalPayload(c.Request().Body, hookPatch); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformed change project webhook").SetInternal(err)
}
+ var activityList []string
+ if hookPatch.ActivityList != nil {
+ activityList = strings.Split(*hookPatch.ActivityList, ",")
+ }
- webhook, err := s.store.PatchProjectWebhook(ctx, hookPatch)
+ webhook, err := s.store.UpdateProjectWebhookV2(ctx, c.Get(getPrincipalIDContextKey()).(int), project.ID, project.ResourceID, id, &store.UpdateProjectWebhookMessage{
+ Title: hookPatch.Name,
+ URL: hookPatch.URL,
+ ActivityList: activityList,
+ })
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project webhook ID not found: %d", id))
@@ -128,7 +157,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, webhook); err != nil {
+ if err := jsonapi.MarshalPayload(c.Response().Writer, webhook.ToAPIProjectWebhook()); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal project webhook change response: %v", id)).SetInternal(err)
}
return nil
@@ -136,7 +165,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
g.DELETE("/project/:projectID/webhook/:webhookID", func(c echo.Context) error {
ctx := c.Request().Context()
- _, err := strconv.Atoi(c.Param("projectID"))
+ projectID, err := strconv.Atoi(c.Param("projectID"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectID"))).SetInternal(err)
}
@@ -146,11 +175,14 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Webhook ID is not a number: %s", c.Param("webhookID"))).SetInternal(err)
}
- hookDelete := &api.ProjectWebhookDelete{
- ID: id,
- DeleterID: c.Get(getPrincipalIDContextKey()).(int),
+ project, err := s.store.GetProjectByID(ctx, projectID)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project ID: %v", projectID)).SetInternal(err)
+ }
+ if project == nil {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project ID not found: %v", projectID))
}
- if err := s.store.DeleteProjectWebhook(ctx, hookDelete); err != nil {
+ if err := s.store.DeleteProjectWebhookV2(ctx, project.ID, project.ResourceID, id); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete project webhook ID: %v", id)).SetInternal(err)
}
@@ -179,7 +211,9 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project webhook ID is not a number: %s", c.Param("webhookID"))).SetInternal(err)
}
- webhook, err := s.store.GetProjectWebhookByID(ctx, id)
+ webhook, err := s.store.GetProjectWebhookV2(ctx, &store.FindProjectWebhookMessage{
+ ID: &id,
+ })
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project webhook ID: %v", id)).SetInternal(err)
}
@@ -199,9 +233,9 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
URL: webhook.URL,
Level: webhookPlugin.WebhookInfo,
ActivityType: string(api.ActivityIssueCreate),
- Title: fmt.Sprintf("Test webhook %q", webhook.Name),
+ Title: fmt.Sprintf("Test webhook %q", webhook.Title),
Description: "This is a test",
- Link: fmt.Sprintf("%s/project/%s/webhook/%s", setting.ExternalUrl, getProjectSlug(project), api.ProjectWebhookSlug(webhook)),
+ Link: fmt.Sprintf("%s/project/%s/webhook/%s", setting.ExternalUrl, getProjectSlug(project), api.ProjectWebhookSlug(webhook.Title, webhook.ID)),
CreatorID: api.SystemBotID,
CreatorName: "Bytebase",
CreatorEmail: "[email protected]",
diff --git a/backend/store/project.go b/backend/store/project.go
index e59ced95bd..430405b0f7 100644
--- a/backend/store/project.go
+++ b/backend/store/project.go
@@ -141,6 +141,7 @@ type ProjectMessage struct {
DBNameTemplate string
SchemaChangeType api.ProjectSchemaChangeType
LGTMCheckSetting api.LGTMCheckSetting
+ Webhooks []*ProjectWebhookMessage
// The following fields are output only and not used for create().
UID int
Deleted bool
@@ -358,7 +359,7 @@ func (s *Store) UpdateProjectV2(ctx context.Context, patch *UpdateProjectMessage
}
// WARNING: calling updateProjectImplV2 from other store library has to invalidate the cache.
-func (*Store) updateProjectImplV2(ctx context.Context, tx *Tx, patch *UpdateProjectMessage) (*ProjectMessage, error) {
+func (s *Store) updateProjectImplV2(ctx context.Context, tx *Tx, patch *UpdateProjectMessage) (*ProjectMessage, error) {
set, args := []string{"updater_id = $1"}, []interface{}{fmt.Sprintf("%d", patch.UpdaterID)}
if v := patch.Title; v != nil {
set, args = append(set, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)
@@ -428,11 +429,16 @@ func (*Store) updateProjectImplV2(ctx context.Context, tx *Tx, patch *UpdateProj
}
return nil, FormatError(err)
}
+ projectWebhooks, err := s.findProjectWebhookImplV2(ctx, tx, &FindProjectWebhookMessage{ProjectID: &project.UID})
+ if err != nil {
+ return nil, err
+ }
+ project.Webhooks = projectWebhooks
project.Deleted = convertRowStatusToDeleted(rowStatus)
return project, nil
}
-func (*Store) listProjectImplV2(ctx context.Context, tx *Tx, find *FindProjectMessage) ([]*ProjectMessage, error) {
+func (s *Store) listProjectImplV2(ctx context.Context, tx *Tx, find *FindProjectMessage) ([]*ProjectMessage, error) {
where, args := []string{"TRUE"}, []interface{}{}
if v := find.ResourceID; v != nil {
where, args = append(where, fmt.Sprintf("resource_id = $%d", len(args)+1)), append(args, *v)
@@ -485,9 +491,16 @@ func (*Store) listProjectImplV2(ctx context.Context, tx *Tx, find *FindProjectMe
); err != nil {
return nil, FormatError(err)
}
- projectMessage.Deleted = convertRowStatusToDeleted(rowStatus)
projectMessages = append(projectMessages, &projectMessage)
}
+ for _, project := range projectMessages {
+ projectWebhooks, err := s.findProjectWebhookImplV2(ctx, tx, &FindProjectWebhookMessage{ProjectID: &project.UID})
+ if err != nil {
+ return nil, err
+ }
+ project.Webhooks = projectWebhooks
+ }
+
return projectMessages, nil
}
diff --git a/backend/store/project_webhook.go b/backend/store/project_webhook.go
index 2ecfa420a5..82a4cc6110 100644
--- a/backend/store/project_webhook.go
+++ b/backend/store/project_webhook.go
@@ -13,235 +13,230 @@ import (
api "github.com/bytebase/bytebase/backend/legacyapi"
)
-// projectWebhookRaw is the store model for an ProjectWebhook.
-// Fields have exactly the same meanings as ProjectWebhook.
-type projectWebhookRaw struct {
- ID int
-
- // Related fields
- ProjectID int
-
- // Domain specific fields
- Type string
- Name string
- URL string
+// ProjectWebhookMessage is the store model for an project webhook.
+type ProjectWebhookMessage struct {
+ // Type is the webhook type (e.g. SLACK, DISCORD, etc.).
+ Type string
+ // Title is the webhook name.
+ Title string
+ // URL is the webhook URL.
+ URL string
+ // ActivityList is the list of activities that the webhook is interested in.
ActivityList []string
+ // Output only fields.
+ //
+ // ID is the unique identifier of the project webhook.
+ ID int
+ ProjectID int
}
-// toProjectWebhook creates an instance of ProjectWebhook based on the projectWebhookRaw.
-// This is intended to be called when we need to compose an ProjectWebhook relationship.
-func (raw *projectWebhookRaw) toProjectWebhook() *api.ProjectWebhook {
- projectWebhook := api.ProjectWebhook{
- ID: raw.ID,
-
- // Related fields
- ProjectID: raw.ProjectID,
-
- // Domain specific fields
- Type: raw.Type,
- Name: raw.Name,
- URL: raw.URL,
- }
- projectWebhook.ActivityList = append(projectWebhook.ActivityList, raw.ActivityList...)
- return &projectWebhook
-}
-
-// CreateProjectWebhook creates an instance of ProjectWebhook.
-func (s *Store) CreateProjectWebhook(ctx context.Context, create *api.ProjectWebhookCreate) (*api.ProjectWebhook, error) {
- projectWebhookRaw, err := s.createProjectWebhookRaw(ctx, create)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to create ProjectWebhook with ProjectWebhookCreate[%+v]", create)
+// ToAPIProjectWebhook converts a ProjectWebhookMessage to an api.ProjectWebhook.
+func (p *ProjectWebhookMessage) ToAPIProjectWebhook() *api.ProjectWebhook {
+ return &api.ProjectWebhook{
+ ID: p.ID,
+ ProjectID: p.ProjectID,
+ Type: p.Type,
+ URL: p.URL,
+ ActivityList: p.ActivityList,
}
- return composeProjectWebhook(projectWebhookRaw), nil
}
-// GetProjectWebhookByID gets an instance of ProjectWebhook.
-func (s *Store) GetProjectWebhookByID(ctx context.Context, id int) (*api.ProjectWebhook, error) {
- find := &api.ProjectWebhookFind{ID: &id}
- projectWebhookRaw, err := s.getProjectWebhookRaw(ctx, find)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to get ProjectWebhook with ID %d", id)
- }
- if projectWebhookRaw == nil {
- return nil, nil
- }
- return composeProjectWebhook(projectWebhookRaw), nil
+// UpdateProjectWebhookMessage is the message for updating project webhooks.
+type UpdateProjectWebhookMessage struct {
+ // Title is the webhook name.
+ Title *string
+ // URL is the webhook URL.
+ URL *string
+ // ActivityList is the list of activities that the webhook is interested in.
+ ActivityList []string
}
-// FindProjectWebhook finds a list of ProjectWebhook instances.
-func (s *Store) FindProjectWebhook(ctx context.Context, find *api.ProjectWebhookFind) ([]*api.ProjectWebhook, error) {
- projectWebhookRawList, err := s.findProjectWebhookRaw(ctx, find)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to find ProjectWebhook list with ProjectWebhookFind[%+v]", find)
- }
- var projectWebhookList []*api.ProjectWebhook
- for _, raw := range projectWebhookRawList {
- projectWebhookList = append(projectWebhookList, composeProjectWebhook(raw))
- }
- return projectWebhookList, nil
+// FindProjectWebhookMessage is the message for finding project webhooks,
+// if all fields are nil, it will list all project webhooks.
+type FindProjectWebhookMessage struct {
+ ID *int
+ ProjectID *int
+ URL *string
+ ActivityType *api.ActivityType
}
-// PatchProjectWebhook patches an instance of ProjectWebhook.
-func (s *Store) PatchProjectWebhook(ctx context.Context, patch *api.ProjectWebhookPatch) (*api.ProjectWebhook, error) {
- projectWebhookRaw, err := s.patchProjectWebhookRaw(ctx, patch)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to patch ProjectWebhook with ProjectWebhookPatch[%+v]", patch)
- }
- return composeProjectWebhook(projectWebhookRaw), nil
-}
+// CreateProjectWebhookV2 creates an instance of ProjectWebhook.
+func (s *Store) CreateProjectWebhookV2(ctx context.Context, principalUID int, projectUID int, projectResourceID string, create *ProjectWebhookMessage) (*ProjectWebhookMessage, error) {
+ query := `
+ INSERT INTO project_webhook (
+ creator_id,
+ updater_id,
+ project_id,
+ type,
+ name,
+ url,
+ activity_list
+ )
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
+ RETURNING id, project_id, type, name, url, activity_list
+ `
+ var projectWebhook ProjectWebhookMessage
+ var txtArray pgtype.TextArray
-// DeleteProjectWebhook deletes an existing projectWebhook by ID.
-func (s *Store) DeleteProjectWebhook(ctx context.Context, delete *api.ProjectWebhookDelete) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
- return FormatError(err)
+ return nil, errors.Wrapf(err, "failed to begin transaction")
}
- defer tx.Rollback()
- if err := s.deleteProjectWebhookImpl(ctx, tx, delete); err != nil {
- return FormatError(err)
+ if err := tx.QueryRowContext(ctx, query,
+ principalUID,
+ principalUID,
+ projectUID,
+ create.Type,
+ create.Title,
+ create.URL,
+ create.ActivityList,
+ ).Scan(
+ &projectWebhook.ID,
+ &projectWebhook.ProjectID,
+ &projectWebhook.Type,
+ &projectWebhook.Title,
+ &projectWebhook.URL,
+ &txtArray,
+ ); err != nil {
+ if err == sql.ErrNoRows {
+ return nil, common.FormatDBErrorEmptyRowWithQuery(query)
+ }
+ return nil, FormatError(err)
+ }
+ if err := txtArray.AssignTo(&projectWebhook.ActivityList); err != nil {
+ return nil, FormatError(err)
}
-
if err := tx.Commit(); err != nil {
- return FormatError(err)
+ return nil, errors.Wrapf(err, "failed to commit transaction")
}
- return nil
-}
-
-//
-// private functions
-//
-
-func composeProjectWebhook(raw *projectWebhookRaw) *api.ProjectWebhook {
- return raw.toProjectWebhook()
+ s.projectCache.Delete(projectResourceID)
+ s.projectIDCache.Delete(projectUID)
+ return &projectWebhook, nil
}
-// createProjectWebhookRaw creates a new projectWebhook.
-func (s *Store) createProjectWebhookRaw(ctx context.Context, create *api.ProjectWebhookCreate) (*projectWebhookRaw, error) {
- tx, err := s.db.BeginTx(ctx, nil)
+// FindProjectWebhookV2 finds a list of ProjectWebhook instances.
+func (s *Store) FindProjectWebhookV2(ctx context.Context, find *FindProjectWebhookMessage) ([]*ProjectWebhookMessage, error) {
+ tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
if err != nil {
- return nil, FormatError(err)
+ return nil, errors.Wrapf(err, "failed to begin transaction")
}
- defer tx.Rollback()
- projectWebhook, err := createProjectWebhookImpl(ctx, tx, create)
+ webhooks, err := s.findProjectWebhookImplV2(ctx, tx, find)
if err != nil {
return nil, err
}
if err := tx.Commit(); err != nil {
- return nil, FormatError(err)
+ return nil, errors.Wrapf(err, "failed to commit transaction")
}
-
- return projectWebhook, nil
+ return webhooks, nil
}
-// findProjectWebhookRaw retrieves a list of projectWebhooks based on find.
-func (s *Store) findProjectWebhookRaw(ctx context.Context, find *api.ProjectWebhookFind) ([]*projectWebhookRaw, error) {
+// GetProjectWebhookV2 gets an instance of ProjectWebhook.
+func (s *Store) GetProjectWebhookV2(ctx context.Context, find *FindProjectWebhookMessage) (*ProjectWebhookMessage, error) {
tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
if err != nil {
- return nil, FormatError(err)
+ return nil, errors.Wrapf(err, "failed to begin transaction")
}
- defer tx.Rollback()
- list, err := findProjectWebhookImpl(ctx, tx, find)
+ webhooks, err := s.findProjectWebhookImplV2(ctx, tx, find)
if err != nil {
return nil, err
}
- return list, nil
-}
-
-// getProjectWebhookRaw retrieves a single projectWebhook based on find.
-// Returns ECONFLICT if finding more than 1 matching records.
-func (s *Store) getProjectWebhookRaw(ctx context.Context, find *api.ProjectWebhookFind) (*projectWebhookRaw, error) {
- tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
- if err != nil {
- return nil, FormatError(err)
- }
- defer tx.Rollback()
-
- list, err := findProjectWebhookImpl(ctx, tx, find)
- if err != nil {
- return nil, err
+ if err := tx.Commit(); err != nil {
+ return nil, errors.Wrapf(err, "failed to commit transaction")
}
- if len(list) == 0 {
+ if len(webhooks) == 0 {
return nil, nil
- } else if len(list) > 1 {
- return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d project hooks with filter %+v, expect 1", len(list), find)}
}
- return list[0], nil
+ if len(webhooks) > 1 {
+ return nil, errors.Errorf("expected find one project webhook wit %+v, but found %d", find, len(webhooks))
+ }
+
+ return webhooks[0], nil
}
-// patchProjectWebhookRaw updates an existing projectWebhook by ID.
-// Returns ENOTFOUND if projectWebhook does not exist.
-func (s *Store) patchProjectWebhookRaw(ctx context.Context, patch *api.ProjectWebhookPatch) (*projectWebhookRaw, error) {
+// UpdateProjectWebhookV2 updates an instance of ProjectWebhook.
+func (s *Store) UpdateProjectWebhookV2(ctx context.Context, principalUID int, projectID int, projectResourceID string, projectWebhookID int, update *UpdateProjectWebhookMessage) (*ProjectWebhookMessage, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
- return nil, FormatError(err)
+ return nil, errors.Wrapf(err, "failed to begin transaction")
}
- defer tx.Rollback()
-
- projectWebhook, err := patchProjectWebhookImpl(ctx, tx, patch)
- if err != nil {
- return nil, FormatError(err)
+ // Build UPDATE clause.
+ set, args := []string{"updater_id = $1"}, []interface{}{principalUID}
+ if v := update.Title; v != nil {
+ set, args = append(set, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)
}
-
- if err := tx.Commit(); err != nil {
- return nil, FormatError(err)
+ if v := update.URL; v != nil {
+ set, args = append(set, fmt.Sprintf("url = $%d", len(args)+1)), append(args, *v)
+ }
+ if v := update.ActivityList; v != nil {
+ set, args = append(set, fmt.Sprintf("activity_list = $%d", len(args)+1)), append(args, v)
}
- return projectWebhook, nil
-}
+ args = append(args, projectWebhookID)
-// createProjectWebhookImpl creates a new projectWebhook.
-func createProjectWebhookImpl(ctx context.Context, tx *Tx, create *api.ProjectWebhookCreate) (*projectWebhookRaw, error) {
- // Insert row into database.
- query := `
- INSERT INTO project_webhook (
- creator_id,
- updater_id,
- project_id,
- type,
- name,
- url,
- activity_list
- )
- VALUES ($1, $2, $3, $4, $5, $6, $7)
- RETURNING id, project_id, type, name, url, activity_list
- `
- var projectWebhookRaw projectWebhookRaw
+ var projectWebhook ProjectWebhookMessage
var txtArray pgtype.TextArray
- if err := tx.QueryRowContext(ctx, query,
- create.CreatorID,
- create.CreatorID,
- create.ProjectID,
- create.Type,
- create.Name,
- create.URL,
- create.ActivityList,
+ // Execute update query with RETURNING.
+ if err := tx.QueryRowContext(ctx, fmt.Sprintf(`
+ UPDATE project_webhook
+ SET `+strings.Join(set, ", ")+`
+ WHERE id = $%d
+ RETURNING id, project_id, type, name, url, activity_list
+`, len(args)),
+ args...,
).Scan(
- &projectWebhookRaw.ID,
- &projectWebhookRaw.ProjectID,
- &projectWebhookRaw.Type,
- &projectWebhookRaw.Name,
- &projectWebhookRaw.URL,
+ &projectWebhook.ID,
+ &projectWebhook.ProjectID,
+ &projectWebhook.Type,
+ &projectWebhook.Title,
+ &projectWebhook.URL,
&txtArray,
); err != nil {
if err == sql.ErrNoRows {
- return nil, common.FormatDBErrorEmptyRowWithQuery(query)
+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("project hook ID not found: %d", projectWebhookID)}
}
return nil, FormatError(err)
}
- if err := txtArray.AssignTo(&projectWebhookRaw.ActivityList); err != nil {
+ if err := txtArray.AssignTo(&projectWebhook.ActivityList); err != nil {
return nil, FormatError(err)
}
- return &projectWebhookRaw, nil
+
+ if err := tx.Commit(); err != nil {
+ return nil, errors.Wrapf(err, "failed to commit transaction")
+ }
+
+ s.projectCache.Delete(projectResourceID)
+ s.projectIDCache.Delete(projectID)
+ return &projectWebhook, nil
}
-func findProjectWebhookImpl(ctx context.Context, tx *Tx, find *api.ProjectWebhookFind) ([]*projectWebhookRaw, error) {
+// DeleteProjectWebhookV2 deletes an existing projectWebhook by projectUID and url.
+func (s *Store) DeleteProjectWebhookV2(ctx context.Context, projectUID int, projectResourceID string, projectWebhookUID int) error {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return errors.Wrapf(err, "failed to begin transaction")
+ }
+
+ if _, err := tx.ExecContext(ctx, `DELETE FROM project_webhook WHERE id = $1`, projectWebhookUID); err != nil {
+ return FormatError(err)
+ }
+
+ if err := tx.Commit(); err != nil {
+ return errors.Wrapf(err, "failed to commit transaction")
+ }
+
+ s.projectCache.Delete(projectResourceID)
+ s.projectIDCache.Delete(projectUID)
+ return nil
+}
+
+func (*Store) findProjectWebhookImplV2(ctx context.Context, tx *Tx, find *FindProjectWebhookMessage) ([]*ProjectWebhookMessage, error) {
// Build WHERE clause.
where, args := []string{"TRUE"}, []interface{}{}
if v := find.ID; v != nil {
@@ -250,11 +245,13 @@ func findProjectWebhookImpl(ctx context.Context, tx *Tx, find *api.ProjectWebhoo
if v := find.ProjectID; v != nil {
where, args = append(where, fmt.Sprintf("project_id = $%d", len(args)+1)), append(args, *v)
}
+ if v := find.URL; v != nil {
+ where, args = append(where, fmt.Sprintf("url = $%d", len(args)+1)), append(args, *v)
+ }
rows, err := tx.QueryContext(ctx, `
SELECT
id,
- project_id,
type,
name,
url,
@@ -268,96 +265,39 @@ func findProjectWebhookImpl(ctx context.Context, tx *Tx, find *api.ProjectWebhoo
}
defer rows.Close()
- // Iterate over result set and deserialize rows into projectWebhookRawList.
- var projectWebhookRawList []*projectWebhookRaw
+ var projectWebhooks []*ProjectWebhookMessage
for rows.Next() {
- var projectWebhookRaw projectWebhookRaw
+ var projectWebhook ProjectWebhookMessage
var txtArray pgtype.TextArray
if err := rows.Scan(
- &projectWebhookRaw.ID,
- &projectWebhookRaw.ProjectID,
- &projectWebhookRaw.Type,
- &projectWebhookRaw.Name,
- &projectWebhookRaw.URL,
+ &projectWebhook.ID,
+ &projectWebhook.Type,
+ &projectWebhook.Title,
+ &projectWebhook.URL,
&txtArray,
); err != nil {
return nil, FormatError(err)
}
- if err := txtArray.AssignTo(&projectWebhookRaw.ActivityList); err != nil {
+ if err := txtArray.AssignTo(&projectWebhook.ActivityList); err != nil {
return nil, FormatError(err)
}
if v := find.ActivityType; v != nil {
- for _, activity := range projectWebhookRaw.ActivityList {
+ for _, activity := range projectWebhook.ActivityList {
if api.ActivityType(activity) == *v {
- projectWebhookRawList = append(projectWebhookRawList, &projectWebhookRaw)
+ projectWebhooks = append(projectWebhooks, &projectWebhook)
break
}
}
} else {
- projectWebhookRawList = append(projectWebhookRawList, &projectWebhookRaw)
+ projectWebhooks = append(projectWebhooks, &projectWebhook)
}
}
if err := rows.Err(); err != nil {
return nil, FormatError(err)
}
- return projectWebhookRawList, nil
-}
-
-// patchProjectWebhookImpl updates a projectWebhook by ID. Returns the new state of the projectWebhook after update.
-func patchProjectWebhookImpl(ctx context.Context, tx *Tx, patch *api.ProjectWebhookPatch) (*projectWebhookRaw, error) {
- // Build UPDATE clause.
- set, args := []string{"updater_id = $1"}, []interface{}{patch.UpdaterID}
- if v := patch.Name; v != nil {
- set, args = append(set, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)
- }
- if v := patch.URL; v != nil {
- set, args = append(set, fmt.Sprintf("url = $%d", len(args)+1)), append(args, *v)
- }
- if v := patch.ActivityList; v != nil {
- activities := strings.Split(*v, ",")
- set, args = append(set, fmt.Sprintf("activity_list = $%d", len(args)+1)), append(args, activities)
- }
-
- args = append(args, patch.ID)
-
- var projectWebhookRaw projectWebhookRaw
- var txtArray pgtype.TextArray
- // Execute update query with RETURNING.
- if err := tx.QueryRowContext(ctx, fmt.Sprintf(`
- UPDATE project_webhook
- SET `+strings.Join(set, ", ")+`
- WHERE id = $%d
- RETURNING id, project_id, type, name, url, activity_list
- `, len(args)),
- args...,
- ).Scan(
- &projectWebhookRaw.ID,
- &projectWebhookRaw.ProjectID,
- &projectWebhookRaw.Type,
- &projectWebhookRaw.Name,
- &projectWebhookRaw.URL,
- &txtArray,
- ); err != nil {
- if err == sql.ErrNoRows {
- return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("project hook ID not found: %d", patch.ID)}
- }
- return nil, FormatError(err)
- }
- if err := txtArray.AssignTo(&projectWebhookRaw.ActivityList); err != nil {
- return nil, FormatError(err)
- }
- return &projectWebhookRaw, nil
-}
-
-// deleteProjectWebhookImpl permanently deletes a projectWebhook by ID.
-func (*Store) deleteProjectWebhookImpl(ctx context.Context, tx *Tx, delete *api.ProjectWebhookDelete) error {
- // Remove row from database.
- if _, err := tx.ExecContext(ctx, `DELETE FROM project_webhook WHERE id = $1`, delete.ID); err != nil {
- return FormatError(err)
- }
- return nil
+ return projectWebhooks, nil
}