github.com/fastly/cli@v1.7.2-0.20240304164155-9d0f1d77c3bf/pkg/commands/service/create.go (about)

     1  package service
     2  
     3  import (
     4  	"io"
     5  
     6  	"github.com/fastly/go-fastly/v9/fastly"
     7  
     8  	"github.com/fastly/cli/pkg/argparser"
     9  	"github.com/fastly/cli/pkg/global"
    10  	"github.com/fastly/cli/pkg/text"
    11  )
    12  
    13  // CreateCommand calls the Fastly API to create services.
    14  type CreateCommand struct {
    15  	argparser.Base
    16  
    17  	// Optional.
    18  	comment argparser.OptionalString
    19  	name    argparser.OptionalString
    20  	stype   argparser.OptionalString
    21  }
    22  
    23  // NewCreateCommand returns a usable command registered under the parent.
    24  func NewCreateCommand(parent argparser.Registerer, g *global.Data) *CreateCommand {
    25  	c := CreateCommand{
    26  		Base: argparser.Base{
    27  			Globals: g,
    28  		},
    29  	}
    30  	c.CmdClause = parent.Command("create", "Create a Fastly service").Alias("add")
    31  
    32  	// Optional.
    33  	c.CmdClause.Flag("comment", "Human-readable comment").Action(c.comment.Set).StringVar(&c.comment.Value)
    34  	c.CmdClause.Flag("name", "Service name").Short('n').Action(c.name.Set).StringVar(&c.name.Value)
    35  	c.CmdClause.Flag("type", `Service type. Can be one of "wasm" or "vcl", defaults to "vcl".`).Default("vcl").Action(c.stype.Set).EnumVar(&c.stype.Value, "wasm", "vcl")
    36  	return &c
    37  }
    38  
    39  // Exec invokes the application logic for the command.
    40  func (c *CreateCommand) Exec(_ io.Reader, out io.Writer) error {
    41  	input := fastly.CreateServiceInput{}
    42  
    43  	if c.name.WasSet {
    44  		input.Name = &c.name.Value
    45  	}
    46  	if c.comment.WasSet {
    47  		input.Comment = &c.comment.Value
    48  	}
    49  	if c.stype.WasSet {
    50  		input.Type = &c.stype.Value
    51  	}
    52  	s, err := c.Globals.APIClient.CreateService(&input)
    53  	if err != nil {
    54  		c.Globals.ErrLog.AddWithContext(err, map[string]any{
    55  			"Service Name": input.Name,
    56  			"Type":         input.Type,
    57  			"Comment":      input.Comment,
    58  		})
    59  		return err
    60  	}
    61  
    62  	text.Success(out, "Created service %s", fastly.ToValue(s.ServiceID))
    63  	return nil
    64  }