github.com/fastly/cli@v1.7.2-0.20240304164155-9d0f1d77c3bf/pkg/commands/dictionaryentry/create.go (about) 1 package dictionaryentry 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 a dictionary item. 14 type CreateCommand struct { 15 argparser.Base 16 Input fastly.CreateDictionaryItemInput 17 itemKey, itemValue string 18 serviceName argparser.OptionalServiceNameID 19 } 20 21 // NewCreateCommand returns a usable command registered under the parent. 22 func NewCreateCommand(parent argparser.Registerer, g *global.Data) *CreateCommand { 23 c := CreateCommand{ 24 Base: argparser.Base{ 25 Globals: g, 26 }, 27 } 28 c.CmdClause = parent.Command("create", "Create a new item on a Fastly edge dictionary") 29 30 // Required. 31 c.CmdClause.Flag("dictionary-id", "Dictionary ID").Required().StringVar(&c.Input.DictionaryID) 32 c.CmdClause.Flag("key", "Dictionary item key").Required().StringVar(&c.itemKey) 33 c.CmdClause.Flag("value", "Dictionary item value").Required().StringVar(&c.itemValue) 34 35 // Optional. 36 c.RegisterFlag(argparser.StringFlagOpts{ 37 Name: argparser.FlagServiceIDName, 38 Description: argparser.FlagServiceIDDesc, 39 Dst: &g.Manifest.Flag.ServiceID, 40 Short: 's', 41 }) 42 c.RegisterFlag(argparser.StringFlagOpts{ 43 Action: c.serviceName.Set, 44 Name: argparser.FlagServiceName, 45 Description: argparser.FlagServiceDesc, 46 Dst: &c.serviceName.Value, 47 }) 48 return &c 49 } 50 51 // Exec invokes the application logic for the command. 52 func (c *CreateCommand) Exec(_ io.Reader, out io.Writer) error { 53 serviceID, source, flag, err := argparser.ServiceID(c.serviceName, *c.Globals.Manifest, c.Globals.APIClient, c.Globals.ErrLog) 54 if err != nil { 55 return err 56 } 57 if c.Globals.Verbose() { 58 argparser.DisplayServiceID(serviceID, flag, source, out) 59 } 60 61 c.Input.ItemKey = &c.itemKey 62 c.Input.ItemValue = &c.itemValue 63 c.Input.ServiceID = serviceID 64 _, err = c.Globals.APIClient.CreateDictionaryItem(&c.Input) 65 if err != nil { 66 c.Globals.ErrLog.AddWithContext(err, map[string]any{ 67 "Service ID": serviceID, 68 }) 69 return err 70 } 71 72 text.Success(out, "Created dictionary item %s (service %s, dictionary %s)", fastly.ToValue(c.Input.ItemKey), c.Input.ServiceID, c.Input.DictionaryID) 73 return nil 74 }