From 4e72cbafb4efedba5e57ab39649767f900675531 Mon Sep 17 00:00:00 2001 From: mark wu Date: Thu, 14 Dec 2023 15:36:43 +0800 Subject: [PATCH] Fallback handling for existing domain --- internal/handler/controller/domain.go | 6 ++++++ internal/handler/controller/domain_test.go | 19 +++++++++++++++---- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/internal/handler/controller/domain.go b/internal/handler/controller/domain.go index 25d3c96..5a8584c 100644 --- a/internal/handler/controller/domain.go +++ b/internal/handler/controller/domain.go @@ -57,6 +57,12 @@ func (c *Controller) handleDomainVerification(w http.ResponseWriter, r *http.Req if !ok { respond(w, func() (any, error) { return nil, models.ErrUndefinedDomain }) } + + domain, _ := c.DB.GetDomainByName(r.Context(), domainName) + if domain != nil { + c.handleDomainCreate(w, r) + return + } respond(w, withTx(r.Context(), c.DB, func(tx db.Tx) (any, error) { var domainVerification *models.DomainVerification domain, _ := tx.GetDomainByName(r.Context(), domainName) diff --git a/internal/handler/controller/domain_test.go b/internal/handler/controller/domain_test.go index 1cfa0ac..1be6b14 100644 --- a/internal/handler/controller/domain_test.go +++ b/internal/handler/controller/domain_test.go @@ -364,16 +364,26 @@ func TestDomainVerification(t *testing.T) { } }) }) + testutil.WithTestController(func(c *testutil.TestController) { + token := setupDomainVerification(c) + db.WithTx(c.Context, c.DB, func(tx db.Tx) error { + return tx.CreateDomain(c.Context, models.NewDomain(time.Now(), "test.com", "test", "main")) + }) + + t.Run("Should raise used domain error", func(t *testing.T) { req := httptest.NewRequest("POST", "http://localtest.me/api/v1/apps/test2/domains/test.com", nil) req.Header.Add("Authorization", "bearer "+token) w := httptest.NewRecorder() c.ServeHTTP(w, req) - domain, err := testutil.DecodeJSONResponse[*api.APIDomain](w.Result()) - if assert.NoError(t, err) { - assert.Nil(t, domain.Domain) - assert.Equal(t, "test.com", domain.DomainVerification.Domain) + _, err := testutil.DecodeJSONResponse[*api.APIDomain](w.Result()) + if assert.Error(t, err) { + assert.Equal(t, 409, err.(api.ServerError).Code) + assert.Equal(t, models.ErrDomainUsedName.Error(), err.(api.ServerError).Message) } }) + + t.Run("Should replace app of the used domain", func(t *testing.T) { + req := httptest.NewRequest("POST", "http://localtest.me/api/v1/apps/test2/domains/test.com?replaceApp=test", nil) req.Header.Add("Authorization", "bearer "+token) w := httptest.NewRecorder() c.ServeHTTP(w, req) @@ -382,6 +392,7 @@ func TestDomainVerification(t *testing.T) { assert.Nil(t, domain.DomainVerification) assert.NotNil(t, domain.Domain) assert.Equal(t, "test.com", domain.Domain.Domain) + assert.Equal(t, "test2", domain.Domain.AppID) } }) })