github.com/arduino/arduino-cloud-cli@v0.0.0-20240517070944-e7a449561083/command/dashboard/create.go (about)

     1  // This file is part of arduino-cloud-cli.
     2  //
     3  // Copyright (C) 2021 ARDUINO SA (http://www.arduino.cc/)
     4  //
     5  // This program is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Affero General Public License as published
     7  // by the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // This program is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13  // GNU Affero General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Affero General Public License
    16  // along with this program.  If not, see <https://www.gnu.org/licenses/>.
    17  
    18  package dashboard
    19  
    20  import (
    21  	"context"
    22  	"errors"
    23  
    24  	"github.com/arduino/arduino-cloud-cli/config"
    25  	"github.com/arduino/arduino-cloud-cli/internal/iot"
    26  	"github.com/arduino/arduino-cloud-cli/internal/template"
    27  )
    28  
    29  // CreateParams contains the parameters needed to create a new dashboard.
    30  type CreateParams struct {
    31  	Name     *string           // Name of the new dashboard
    32  	Override map[string]string // Template parameters to be overridden
    33  	Template string            // Path of the template file
    34  }
    35  
    36  // Create allows to create a new dashboard.
    37  func Create(ctx context.Context, params *CreateParams, cred *config.Credentials) (*DashboardInfo, error) {
    38  	iotClient, err := iot.NewClient(cred)
    39  	if err != nil {
    40  		return nil, err
    41  	}
    42  
    43  	dashboard, err := template.LoadDashboard(ctx, params.Template, params.Override, iotClient)
    44  	if err != nil {
    45  		return nil, err
    46  	}
    47  
    48  	// Name passed as parameter has priority over name from template
    49  	if params.Name != nil {
    50  		dashboard.Name = *params.Name
    51  	}
    52  	// If name is not specified in the template, it should be passed as parameter
    53  	if dashboard.Name == "" {
    54  		return nil, errors.New("dashboard name not specified")
    55  	}
    56  
    57  	newDashboard, err := iotClient.DashboardCreate(ctx, dashboard)
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  
    62  	return getDashboardInfo(newDashboard), nil
    63  }