-
Notifications
You must be signed in to change notification settings - Fork 145
/
create.go
63 lines (50 loc) · 1.69 KB
/
create.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package tenants
import (
"errors"
"github.com/hatchet-dev/hatchet/api/v1/server/oas/apierrors"
"github.com/hatchet-dev/hatchet/api/v1/server/oas/gen"
"github.com/hatchet-dev/hatchet/api/v1/server/oas/transformers"
"github.com/hatchet-dev/hatchet/internal/repository"
"github.com/hatchet-dev/hatchet/internal/repository/prisma/db"
"github.com/labstack/echo/v4"
)
func (t *TenantService) TenantCreate(ctx echo.Context, request gen.TenantCreateRequestObject) (gen.TenantCreateResponseObject, error) {
user := ctx.Get("user").(*db.UserModel)
// validate the request
if apiErrors, err := t.config.Validator.ValidateAPI(request.Body); err != nil {
return nil, err
} else if apiErrors != nil {
return gen.TenantCreate400JSONResponse(*apiErrors), nil
}
// determine if a tenant with the slug already exists
existingTenant, err := t.config.Repository.Tenant().GetTenantBySlug(string(request.Body.Slug))
if err != nil && !errors.Is(err, db.ErrNotFound) {
return nil, err
}
if existingTenant != nil {
// just return bad request
return gen.TenantCreate400JSONResponse(
apierrors.NewAPIErrors("Tenant with the slug already exists."),
), nil
}
createOpts := &repository.CreateTenantOpts{
Slug: request.Body.Slug,
Name: request.Body.Name,
}
// write the user to the db
tenant, err := t.config.Repository.Tenant().CreateTenant(createOpts)
if err != nil {
return nil, err
}
// add the user as an owner of the tenant
_, err = t.config.Repository.Tenant().CreateTenantMember(tenant.ID, &repository.CreateTenantMemberOpts{
UserId: user.ID,
Role: "OWNER",
})
if err != nil {
return nil, err
}
return gen.TenantCreate200JSONResponse(
*transformers.ToTenant(tenant),
), nil
}