|
| 1 | +package cron_jobs |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "log" |
| 8 | + |
| 9 | + "github.com/hostinger/api-cli/api" |
| 10 | + "github.com/hostinger/api-cli/output" |
| 11 | + "github.com/spf13/cobra" |
| 12 | +) |
| 13 | + |
| 14 | +var CreateCmd = &cobra.Command{ |
| 15 | + Use: "create <username>", |
| 16 | + Short: "Create account cron job", |
| 17 | + Long: "Creates a cron job for the specified account from a schedule expression and a command.\n\nReturns the created cron job, including its uid, which is required to delete the cron job or fetch its output.", |
| 18 | + Args: cobra.MatchAll(cobra.ExactArgs(1)), |
| 19 | + Run: func(cmd *cobra.Command, args []string) { |
| 20 | + payload, err := json.Marshal(createBody(cmd)) |
| 21 | + if err != nil { |
| 22 | + log.Fatal(err) |
| 23 | + } |
| 24 | + r, err := api.Request().HostingCreateAccountCronJobV1WithBodyWithResponse(context.TODO(), args[0], "application/json", bytes.NewReader(payload)) |
| 25 | + if err != nil { |
| 26 | + log.Fatal(err) |
| 27 | + } |
| 28 | + |
| 29 | + output.Format(cmd, r.Body, r.StatusCode()) |
| 30 | + }, |
| 31 | +} |
| 32 | + |
| 33 | +func init() { |
| 34 | + CreateCmd.Flags().StringP("command", "", "", "Command to execute on the schedule.") |
| 35 | + CreateCmd.Flags().StringP("time", "", "", "Cron schedule expression (for example \"0 2 * * *\" runs daily at 02:00).") |
| 36 | + CreateCmd.MarkFlagRequired("command") |
| 37 | + CreateCmd.MarkFlagRequired("time") |
| 38 | +} |
| 39 | + |
| 40 | +func createBody(cmd *cobra.Command) map[string]any { |
| 41 | + body := map[string]any{} |
| 42 | + commandVal, _ := cmd.Flags().GetString("command") |
| 43 | + body["command"] = commandVal |
| 44 | + timeVal, _ := cmd.Flags().GetString("time") |
| 45 | + body["time"] = timeVal |
| 46 | + return body |
| 47 | +} |
0 commit comments