github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/cmd/srv-applet-mgr/apis/middleware/project_provider.go (about)

     1  package middleware
     2  
     3  import (
     4  	"context"
     5  	"strings"
     6  
     7  	"github.com/pkg/errors"
     8  
     9  	"github.com/machinefi/w3bstream/pkg/depends/kit/logr"
    10  	"github.com/machinefi/w3bstream/pkg/depends/x/misc/must"
    11  	"github.com/machinefi/w3bstream/pkg/enums"
    12  	"github.com/machinefi/w3bstream/pkg/errors/status"
    13  	"github.com/machinefi/w3bstream/pkg/modules/account_identity"
    14  )
    15  
    16  func MaybeProjectName(ctx context.Context) (string, bool) {
    17  	if p, ok := ctx.Value("ProjectProvider").(*ProjectProvider); ok && p != nil {
    18  		return p.ProjectName, true
    19  	}
    20  	return "", false
    21  }
    22  
    23  func MustProjectName(ctx context.Context) string {
    24  	p, ok := ctx.Value("ProjectProvider").(*ProjectProvider)
    25  	must.BeTrue(ok)
    26  	return p.ProjectName
    27  }
    28  
    29  func ProjectNameForDisplay(name string) (string, error) {
    30  	parts := strings.SplitN(name, "_", 3)
    31  	if len(parts) != 3 {
    32  		return "", errors.Errorf("unexpected project name format: %s", name)
    33  	}
    34  	if parts[0] != "aid" && parts[0] != "eth" {
    35  		return "", errors.Errorf("unexpected project name format: %s", name)
    36  	}
    37  	return parts[2], nil
    38  }
    39  
    40  func ProjectNameModifier(ctx context.Context) (prefix string, err error) {
    41  	ca, ok := CurrentAccountFromContext(ctx)
    42  	if !ok {
    43  		return "", status.CurrentAccountAbsence
    44  	}
    45  
    46  	prefix = "aid_" + ca.AccountID.String() + "_"
    47  	aci, err := account_identity.GetBySFIDAndType(
    48  		ctx,
    49  		ca.AccountID,
    50  		enums.ACCOUNT_IDENTITY_TYPE__ETHADDRESS,
    51  	)
    52  	if err == nil {
    53  		prefix = "eth_" + aci.IdentityID + "_"
    54  	}
    55  	return prefix, nil
    56  }
    57  
    58  // ProjectProvider with account id prefix
    59  type ProjectProvider struct {
    60  	ProjectName string `name:"projectName" in:"path" validate:"@projectName"`
    61  }
    62  
    63  func (ProjectProvider) ContextKey() string { return "ProjectProvider" }
    64  
    65  func (ProjectProvider) Path() string {
    66  	return "/x/:projectName"
    67  }
    68  
    69  func (r *ProjectProvider) Output(ctx context.Context) (interface{}, error) {
    70  	ctx, l := logr.Start(ctx, "api.mw.ProjectNameModifier")
    71  	defer l.End()
    72  
    73  	prefix, err := ProjectNameModifier(ctx)
    74  	if err != nil {
    75  		return nil, err
    76  	}
    77  	return &ProjectProvider{
    78  		ProjectName: prefix + r.ProjectName,
    79  	}, nil
    80  }