github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/cmd/cli/commands/generate/endpoint/generator.go (about)

     1  // This file is part of the Smart Home
     2  // Program complex distribution https://github.com/e154/smart-home
     3  // Copyright (C) 2016-2023, Filippov Alex
     4  //
     5  // This library is free software: you can redistribute it and/or
     6  // modify it under the terms of the GNU Lesser General Public
     7  // License as published by the Free Software Foundation; either
     8  // version 3 of the License, or (at your option) any later version.
     9  //
    10  // This library 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 GNU
    13  // Library General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public
    16  // License along with this library.  If not, see
    17  // <https://www.gnu.org/licenses/>.
    18  
    19  package endpoint
    20  
    21  import (
    22  	"os"
    23  	"path"
    24  	"strings"
    25  	"text/template"
    26  
    27  	"github.com/e154/smart-home/common/logger"
    28  
    29  	"github.com/e154/smart-home/cmd/cli/commands/generate"
    30  	"github.com/e154/smart-home/common"
    31  	"github.com/spf13/cobra"
    32  )
    33  
    34  var (
    35  	log = logger.MustGetLogger("endpoint")
    36  )
    37  
    38  var endpointTpl = `//CODE GENERATED AUTOMATICALLY
    39  
    40  package {{.Package}}
    41  
    42  import (
    43  	"{{.Dir}}/common"
    44  	m "{{.Dir}}/models"
    45  	"{{.Dir}}/system/validation"
    46  	"github.com/go-playground/validator/v10"
    47  )
    48  
    49  // {{.Name}} ...
    50  type {{.Name}} struct {
    51  	*CommonEndpoint
    52  }
    53  
    54  // New{{.Name}} ...
    55  func New{{.Name}}(common *CommonEndpoint) *{{.Name}} {
    56  	return &{{.Name}}{
    57  		CommonEndpoint: common,
    58  	}
    59  }
    60  
    61  // AddEntity ...
    62  func (n *{{.Name}}) AddEntity(params m.{{.ModelName}}) (result m.{{.ModelName}}, errs validator.ValidationErrorsTranslations, err error) {
    63  
    64  	var ok bool
    65  	if ok, errs = n.validation.Valid(params); !ok {
    66  		return 
    67  	}
    68  
    69  	var id int64
    70  	if id, err = n.adaptors.{{.AdaptorName}}.AddEntity(params); err != nil {
    71  		return
    72  	}
    73  
    74  	result, err = n.adaptors.{{.AdaptorName}}.GetById(id)
    75  
    76  	return
    77  }
    78  
    79  // GetByName ...
    80  func (n *{{.Name}}) GetById(id int64) (result m.{{.ModelName}}, err error) {
    81  
    82  	result, err = n.adaptors.{{.AdaptorName}}.GetById(id)
    83  
    84  	return
    85  }
    86  
    87  // UpdateEntity ...
    88  func (n *{{.Name}}) UpdateEntity(params m.{{.ModelName}}) (result m.{{.ModelName}}, errs validator.ValidationErrorsTranslations, err error) {
    89  
    90  	var user m.{{.ModelName}}
    91  	if user, err = n.adaptors.{{.AdaptorName}}.GetById(params.Id); err != nil {
    92  		return
    93  	}
    94  
    95  	common.Copy(&user, &params, common.JsonEngine)
    96  
    97  	var ok bool
    98  	if ok, errs = n.validation.Valid(user); !ok {
    99  		return 
   100  	}
   101  
   102  	if err = n.adaptors.{{.AdaptorName}}.UpdateEntity(user); err != nil {
   103  		return
   104  	}
   105  
   106  	result, err = n.adaptors.{{.AdaptorName}}.GetById(user.Id)
   107  
   108  	return
   109  }
   110  
   111  // GetList ...
   112  func (n *{{.Name}}) GetList(limit, offset int64, order, sortBy string) (result []m.{{.ModelName}}, total int64, err error) {
   113  	result, total, err = n.adaptors.{{.AdaptorName}}.List(limit, offset, order, sortBy)
   114  	return
   115  }
   116  
   117  // Delete ...
   118  func (n *{{.Name}}) Delete(id int64) (err error) {
   119  
   120  	if _, err = n.adaptors.{{.AdaptorName}}.GetById(id); err != nil {
   121  		return
   122  	}
   123  
   124  	err = n.adaptors.{{.AdaptorName}}.Delete(id)
   125  
   126  	return
   127  }
   128  
   129  // Search ...
   130  func (n *{{.Name}}) Search(query string, limit, offset int) (result []m.{{.ModelName}}, total int64, err error) {
   131  
   132  	//result, total, err = n.adaptors.{{.AdaptorName}}.Search(query, limit, offset)
   133  
   134  	return
   135  }
   136  `
   137  
   138  var (
   139  	endpointCmd = &cobra.Command{
   140  		Use:   "e",
   141  		Short: "endpoint generator",
   142  		Long:  "$ cli g e [-m=ModelName, -a=AdaptorName] [endpointName]",
   143  	}
   144  	modelName   string
   145  	adaptorName string
   146  	packageName = "endpoint"
   147  )
   148  
   149  func init() {
   150  	generate.Generate.AddCommand(endpointCmd)
   151  	endpointCmd.Flags().StringVarP(&modelName, "model", "m", "interface{}", "interface{}")
   152  	endpointCmd.Flags().StringVarP(&adaptorName, "adaptor", "a", "interface{}", "interface{}")
   153  	endpointCmd.Run = func(cmd *cobra.Command, args []string) {
   154  
   155  		if len(args) == 0 {
   156  			log.Error("Wrong number of arguments. Run: cli help generate")
   157  			return
   158  		}
   159  
   160  		currpath, _ := os.Getwd()
   161  
   162  		g := Generator{}
   163  		g.Generate(args[0], currpath)
   164  	}
   165  }
   166  
   167  // Generator ...
   168  type Generator struct{}
   169  
   170  // Generate ...
   171  func (e Generator) Generate(endpointName, currpath string) {
   172  
   173  	log.Infof("Using '%sEndpoint' as endpoint name", endpointName)
   174  	log.Infof("Using '%s' as package name", packageName)
   175  
   176  	fp := path.Join(currpath, "endpoint")
   177  
   178  	e.addEndpoint(fp, endpointName)
   179  }
   180  
   181  func (e Generator) addEndpoint(fp, endpointName string) {
   182  
   183  	if _, err := os.Stat(fp); os.IsNotExist(err) {
   184  		// Create the endpoint's directory
   185  		if err := os.MkdirAll(fp, 0777); err != nil {
   186  			log.Errorf("Could not create endpoints directory: %s", err.Error())
   187  			return
   188  		}
   189  	}
   190  
   191  	fpath := path.Join(fp, strings.ToLower(endpointName)+".go")
   192  	f, err := os.OpenFile(fpath, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666)
   193  	if err != nil {
   194  		log.Errorf("Could not create endpoint file: %s", err.Error())
   195  		return
   196  	}
   197  	defer f.Close()
   198  
   199  	templateData := struct {
   200  		Package     string
   201  		Name        string
   202  		List        string
   203  		ModelName   string
   204  		AdaptorName string
   205  		Dir         string
   206  	}{
   207  		Dir:         common.Dir(),
   208  		Package:     packageName,
   209  		Name:        endpointName,
   210  		ModelName:   modelName,
   211  		AdaptorName: adaptorName,
   212  	}
   213  	t := template.Must(template.New("endpoint").Parse(endpointTpl))
   214  
   215  	if t.Execute(f, templateData) != nil {
   216  		log.Error(err.Error())
   217  	}
   218  
   219  	common.FormatSourceCode(fpath)
   220  }