Подготовка шаблонных функций
This commit is contained in:
parent
49e39dbe0e
commit
78db886bca
31
example.yml
31
example.yml
|
@ -60,30 +60,29 @@ backend:
|
|||
help: Tile server for download tiles map
|
||||
rest:
|
||||
/reference/test1:
|
||||
name: test1
|
||||
groupName: nogroup
|
||||
data:
|
||||
id: 00000000-0000-0000-0000-000000000000
|
||||
id: d62df683-7e0c-4b96-b8e6-11c660f58ff8
|
||||
name: db.test1
|
||||
visible:
|
||||
- id: 00000000-0000-0000-0000-000000000000
|
||||
name: F1
|
||||
filter:
|
||||
- id: 00000000-0000-0000-0000-000000000000
|
||||
name: F1
|
||||
- id: e14d5504-fc3b-4ea1-9b5d-22bfa77fce94
|
||||
name: f1
|
||||
editable: true
|
||||
fieldId:
|
||||
id: 00000000-0000-0000-0000-000000000000
|
||||
name: id
|
||||
roles:
|
||||
GET:
|
||||
- APP_ADMIN
|
||||
LIST:
|
||||
- APP_ADMIN
|
||||
POST:
|
||||
- APP_ADMIN
|
||||
PUT:
|
||||
- APP_ADMIN
|
||||
DELETE:
|
||||
- APP_ADMIN
|
||||
DELETE:
|
||||
- APP_ADMIN
|
||||
GET:
|
||||
- APP_ADMIN
|
||||
LIST:
|
||||
- APP_ADMIN
|
||||
POST:
|
||||
- APP_ADMIN
|
||||
PUT:
|
||||
- APP_ADMIN
|
||||
frontend:
|
||||
lang: angular
|
||||
theme: primeng/resources/themes/mdc-light-indigo/theme.css
|
||||
|
|
|
@ -0,0 +1,34 @@
|
|||
package lib
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"path/filepath"
|
||||
|
||||
"git.ymnuktech.ru/ymnuk/yt-gen-app/lib/templ"
|
||||
"git.ymnuktech.ru/ymnuk/yt-gen-app/structs"
|
||||
)
|
||||
|
||||
func generateBackendRest() {
|
||||
|
||||
type RestStruct struct {
|
||||
Path string
|
||||
Project *structs.Project
|
||||
Rest *structs.Rest
|
||||
}
|
||||
|
||||
if len(Project.Backend.Rest) > 0 {
|
||||
for i := range Project.Backend.Rest {
|
||||
restStruct := &RestStruct{
|
||||
Project: Project,
|
||||
Path: i,
|
||||
Rest: Project.Backend.Rest[i],
|
||||
}
|
||||
destPath := filepath.Join(AppConfig.OutdirBackend, "route", "api", i)
|
||||
fmt.Println(destPath)
|
||||
if err := templ.PrepareTmplFile("tmpl/backend/route/api/templ/index.tmpl", restStruct, filepath.Join(destPath, "index.go")); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -2,7 +2,6 @@ package lib
|
|||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
|
@ -23,14 +22,14 @@ func Backend() {
|
|||
}
|
||||
if len(dirs) > 0 {
|
||||
for _, dir := range dirs {
|
||||
if err := os.MkdirAll(dir, 0775); err != nil {
|
||||
if err := templ.MkdirIsNotExists(dir); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
generateBackendTmpl()
|
||||
generateDB()
|
||||
generateBackendTmpl()
|
||||
|
||||
execCommands()
|
||||
}
|
||||
|
@ -121,6 +120,8 @@ func generateBackendTmpl() {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
generateBackendRest()
|
||||
}
|
||||
|
||||
func generateModelBase() {
|
||||
|
|
|
@ -4,6 +4,7 @@ import (
|
|||
"log"
|
||||
"strings"
|
||||
|
||||
"git.ymnuktech.ru/ymnuk/yt-gen-app/lib/templ"
|
||||
"git.ymnuktech.ru/ymnuk/yt-gen-app/structs"
|
||||
uuid "github.com/satori/go.uuid"
|
||||
)
|
||||
|
@ -32,8 +33,46 @@ func prepareRest(project *structs.Project) *structs.Project {
|
|||
switch strings.ToLower(dataArr[0]) {
|
||||
case "db":
|
||||
project.Backend.Rest[i].Data.ID = findSourceDataInDBByName(project, dataArr[1])
|
||||
// Обработаем поля для Edit
|
||||
if len(project.Backend.Rest[i].Edit) > 0 {
|
||||
for j := range project.Backend.Rest[i].Edit {
|
||||
if project.Backend.Rest[i].Edit[j].ID == uuid.Nil {
|
||||
project.Backend.Rest[i].Edit[j].Name = templ.FieldDBName(&structs.Field{
|
||||
Name: project.Backend.Rest[i].Edit[j].Name,
|
||||
})
|
||||
project.Backend.Rest[i].Edit[j].ID = findFieldIdInDBByName(project, project.Backend.Rest[i].Data.ID, project.Backend.Rest[i].Edit[j].Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Обработаем поля для Filter
|
||||
if len(project.Backend.Rest[i].Filter) > 0 {
|
||||
for j := range project.Backend.Rest[i].Filter {
|
||||
if project.Backend.Rest[i].Filter[j].ID == uuid.Nil {
|
||||
project.Backend.Rest[i].Filter[j].Name = templ.FieldDBName(&structs.Field{
|
||||
Name: project.Backend.Rest[i].Filter[j].Name,
|
||||
})
|
||||
project.Backend.Rest[i].Filter[j].ID = findFieldIdInDBByName(project, project.Backend.Rest[i].Data.ID, project.Backend.Rest[i].Filter[j].Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
case "interface":
|
||||
project.Backend.Rest[i].Data.ID = findSourceDataInInterfaceByName(project, dataArr[1])
|
||||
// Обработаем поля для Edit
|
||||
if len(project.Backend.Rest[i].Edit) > 0 {
|
||||
for j := range project.Backend.Rest[i].Edit {
|
||||
if project.Backend.Rest[i].Edit[j].ID == uuid.Nil {
|
||||
project.Backend.Rest[i].Edit[j].ID = findFieldIdInInterfaceByName(project, project.Backend.Rest[i].Data.ID, project.Backend.Rest[i].Edit[j].Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Обработаем поля для Filter
|
||||
if len(project.Backend.Rest[i].Filter) > 0 {
|
||||
for j := range project.Backend.Rest[i].Filter {
|
||||
if project.Backend.Rest[i].Filter[j].ID == uuid.Nil {
|
||||
project.Backend.Rest[i].Filter[j].ID = findFieldIdInInterfaceByName(project, project.Backend.Rest[i].Data.ID, project.Backend.Rest[i].Filter[j].Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
log.Fatal("Неизвестный формат источника")
|
||||
}
|
||||
|
@ -57,12 +96,26 @@ func prepareRest(project *structs.Project) *structs.Project {
|
|||
|
||||
project.Backend.Rest[i].Data.Name = findSourceDataInDBByID(project, project.Backend.Rest[i].Data.ID)
|
||||
if project.Backend.Rest[i].Data.ID != uuid.Nil {
|
||||
for j := range project.Backend.Rest[i].Edit {
|
||||
project.Backend.Rest[i].Data.Name = findFieldNameInDBById(project, project.Backend.Rest[i].Data.ID, project.Backend.Rest[i].Edit[j].ID)
|
||||
}
|
||||
for j := range project.Backend.Rest[i].Filter {
|
||||
project.Backend.Rest[i].Data.Name = findFieldNameInDBById(project, project.Backend.Rest[i].Data.ID, project.Backend.Rest[i].Filter[j].ID)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
project.Backend.Rest[i].Data.Name = findSourceDataInInterfaceByID(project, project.Backend.Rest[i].Data.ID)
|
||||
if project.Backend.Rest[i].Data.ID == uuid.Nil {
|
||||
log.Fatal("Не найдена структура данных для REST")
|
||||
}
|
||||
|
||||
for j := range project.Backend.Rest[i].Edit {
|
||||
project.Backend.Rest[i].Edit[j].Name = findFieldNameInInterfaceById(project, project.Backend.Rest[i].Data.ID, project.Backend.Rest[i].Edit[j].ID)
|
||||
}
|
||||
for j := range project.Backend.Rest[i].Filter {
|
||||
project.Backend.Rest[i].Edit[j].Name = findFieldNameInInterfaceById(project, project.Backend.Rest[i].Data.ID, project.Backend.Rest[i].Filter[j].ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -82,6 +135,23 @@ func findSourceDataInDBByName(project *structs.Project, name string) uuid.UUID {
|
|||
return uuid.Nil
|
||||
}
|
||||
|
||||
// Найти ID поля по имени
|
||||
func findFieldIdInDBByName(project *structs.Project, tblID uuid.UUID, fldName string) uuid.UUID {
|
||||
if len(project.DB.Tables) == 0 {
|
||||
return uuid.Nil
|
||||
}
|
||||
for i := range project.DB.Tables {
|
||||
if project.DB.Tables[i].ID == tblID {
|
||||
for j := range project.DB.Tables[i].Fields {
|
||||
if project.DB.Tables[i].Fields[j].Name == strings.ToLower(fldName) {
|
||||
return project.DB.Tables[i].Fields[j].ID
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return uuid.Nil
|
||||
}
|
||||
|
||||
// Найти имя таблицы по ID
|
||||
func findSourceDataInDBByID(project *structs.Project, id uuid.UUID) string {
|
||||
if len(project.DB.Tables) == 0 {
|
||||
|
@ -95,6 +165,23 @@ func findSourceDataInDBByID(project *structs.Project, id uuid.UUID) string {
|
|||
return ""
|
||||
}
|
||||
|
||||
// Найти имя поля в таблице по ID
|
||||
func findFieldNameInDBById(project *structs.Project, tblID uuid.UUID, fldId uuid.UUID) string {
|
||||
if len(project.DB.Tables) == 0 {
|
||||
return ""
|
||||
}
|
||||
for i := range project.DB.Tables {
|
||||
if project.DB.Tables[i].ID == tblID {
|
||||
for j := range project.DB.Tables[i].Fields {
|
||||
if project.DB.Tables[i].Fields[j].ID == fldId {
|
||||
return project.DB.Tables[i].Fields[j].Name
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func findSourceDataInInterfaceByName(project *structs.Project, name string) uuid.UUID {
|
||||
// TODO
|
||||
log.Fatal("Функция в разработки")
|
||||
|
@ -106,3 +193,27 @@ func findSourceDataInInterfaceByID(project *structs.Project, id uuid.UUID) strin
|
|||
log.Fatal("Функция в разработки")
|
||||
return ""
|
||||
}
|
||||
|
||||
// Найти ID поля по имени
|
||||
func findFieldIdInInterfaceByName(project *structs.Project, tblID uuid.UUID, fldName string) uuid.UUID {
|
||||
// TODO
|
||||
log.Fatal("Функция в разработки")
|
||||
return uuid.Nil
|
||||
}
|
||||
|
||||
// Найти имя поля в интерфейсе по ID
|
||||
func findFieldNameInInterfaceById(project *structs.Project, tblID uuid.UUID, fldId uuid.UUID) string {
|
||||
if len(project.DB.Tables) == 0 {
|
||||
return ""
|
||||
}
|
||||
for i := range project.DB.Tables {
|
||||
if project.DB.Tables[i].ID == tblID {
|
||||
for j := range project.DB.Tables[i].Fields {
|
||||
if project.DB.Tables[i].Fields[j].ID == fldId {
|
||||
return project.DB.Tables[i].Fields[j].Name
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
|
|
@ -0,0 +1,19 @@
|
|||
package templ
|
||||
|
||||
import (
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"git.ymnuktech.ru/ymnuk/yt-gen-app/structs"
|
||||
)
|
||||
|
||||
func FieldJsonName(field *structs.Field) string {
|
||||
if field == nil {
|
||||
log.Fatal("переданное поле не должно быть пустым")
|
||||
}
|
||||
str := FieldNamePrepare(field.Name)
|
||||
|
||||
str = strings.ToLower(string([]rune(str)[0])) + string([]rune(str)[1:])
|
||||
|
||||
return str
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package templ
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"git.ymnuktech.ru/ymnuk/yt-gen-app/structs"
|
||||
)
|
||||
|
||||
func MethodNameGetId(value string) string {
|
||||
value = FieldName(&structs.Field{
|
||||
Name: strings.ReplaceAll(value, "/", "_"),
|
||||
})
|
||||
return value
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package templ
|
||||
|
||||
func MethodSummary(value string) string {
|
||||
// TODO
|
||||
//log.Fatal("not released")
|
||||
return value
|
||||
}
|
||||
|
||||
func MethodComment(value string) string {
|
||||
// TODO
|
||||
//log.Fatal("not released")
|
||||
return value
|
||||
}
|
||||
|
||||
func GetModelName(value string) string {
|
||||
// TODO
|
||||
//log.Fatal("not released")
|
||||
return value
|
||||
}
|
||||
|
||||
func DisplayMethodNamePost(value string) string {
|
||||
// TODO
|
||||
//log.Fatal("not released")
|
||||
return value
|
||||
}
|
||||
|
||||
func MethodNamePost(value string) string {
|
||||
// TODO
|
||||
//log.Fatal("not released")
|
||||
return value
|
||||
}
|
||||
|
||||
func DisplayMethodNameGet(value string) string {
|
||||
// TODO
|
||||
//log.Fatal("not released")
|
||||
return value
|
||||
}
|
||||
|
||||
func MethodNameGet(value string) string {
|
||||
// TODO
|
||||
//log.Fatal("not released")
|
||||
return value
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package templ
|
||||
|
||||
import (
|
||||
"log"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func PackageName(name string) string {
|
||||
name = strings.Trim(name, " ")
|
||||
if name == "" {
|
||||
log.Fatal("Пустое название пакета")
|
||||
}
|
||||
name = strings.ReplaceAll(name, "/", "_")
|
||||
if []rune(name)[0] == '/' {
|
||||
name = string([]rune(name)[1:])
|
||||
}
|
||||
return strings.ToLower(name)
|
||||
}
|
|
@ -4,9 +4,11 @@ import (
|
|||
"bufio"
|
||||
"bytes"
|
||||
"embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
@ -27,6 +29,17 @@ var funcMap = template.FuncMap{
|
|||
"configParamName": ConfigParamName,
|
||||
"configParamType": ConfigParamType,
|
||||
"configParamTag": ConfigParamTag,
|
||||
"packageName": PackageName,
|
||||
|
||||
"methodNameGetId": MethodNameGetId,
|
||||
|
||||
"methodSummary": MethodSummary,
|
||||
"methodComment": MethodComment,
|
||||
"getModelName": GetModelName,
|
||||
"displayMethodNamePost": DisplayMethodNamePost,
|
||||
"methodNamePost": MethodNamePost,
|
||||
"displayMethodNameGet": DisplayMethodNameGet,
|
||||
"methodNameGet": MethodNameGet,
|
||||
}
|
||||
|
||||
func FieldNamePrepare(value string) string {
|
||||
|
@ -154,7 +167,8 @@ func FieldDescript(field *structs.Field) (str string) {
|
|||
if field.Description != "" {
|
||||
str += fmt.Sprintf(";comment:%s", field.Description)
|
||||
}
|
||||
str += "\"`"
|
||||
str += "\""
|
||||
str = fmt.Sprintf("%s json:\"%s,omitempty\"`", str, FieldJsonName(field))
|
||||
|
||||
return
|
||||
}
|
||||
|
@ -254,3 +268,26 @@ func PrepareTmplFile(filename string, data interface{}, outname string) (err err
|
|||
os.WriteFile(outname, b.Bytes(), 0755)
|
||||
return
|
||||
}
|
||||
|
||||
func PrepareTmplIsNotExists(filename string, data interface{}, outname string) (err error) {
|
||||
|
||||
if err = MkdirIsNotExists(filepath.Dir(outname)); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := os.Stat(outname); errors.Is(err, os.ErrNotExist) {
|
||||
return PrepareTmplFile(filename, data, outname)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func MkdirIsNotExists(pathdir string) (err error) {
|
||||
if _, err = os.Stat(pathdir); os.IsNotExist(err) {
|
||||
if err = os.MkdirAll(pathdir, 0775); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
err = nil
|
||||
return
|
||||
}
|
||||
|
|
|
@ -30,3 +30,34 @@ func InRole(idUser uuid.UUID, roleName string) bool {
|
|||
|
||||
return false
|
||||
}
|
||||
|
||||
func InsRole(idUser uuid.UUID, roleNames []string) bool {
|
||||
|
||||
if len(roleNames) == 0{
|
||||
return true
|
||||
}
|
||||
|
||||
var err error
|
||||
tx := db.BeginTransation()
|
||||
|
||||
defer func() {
|
||||
db.EndTransaction(tx, err)
|
||||
}()
|
||||
|
||||
var userRoles []model.UserRole
|
||||
if res := tx.Joins("Role").Find(&userRoles, "id_user = ?", idUser); res.RowsAffected == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
if len(userRoles) > 0 {
|
||||
for _, item := range userRoles {
|
||||
for _,item2:=range roleNames{
|
||||
if item.Role.Name == item2 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package {{ .Name }}
|
||||
|
||||
import "github.com/labstack/echo/v4"
|
||||
|
||||
func restCount(c echo.Context) error {
|
||||
return c.JSON(http.StatusLocked, structs.Result{
|
||||
Result: &[]bool{false}[0],
|
||||
Code: &[]int{http.StatusLocked}[0]
|
||||
})
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package {{ .Name }}
|
||||
|
||||
import "github.com/labstack/echo/v4"
|
||||
|
||||
func restDelete(c echo.Context) error {
|
||||
return c.JSON(http.StatusLocked, structs.Result{
|
||||
Result: &[]bool{false}[0],
|
||||
Code: &[]int{http.StatusLocked}[0]
|
||||
})
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package {{ .Name }}
|
||||
|
||||
import "github.com/labstack/echo/v4"
|
||||
|
||||
func restGet(c echo.Context) error {
|
||||
return c.JSON(http.StatusLocked, structs.Result{
|
||||
Result: &[]bool{false}[0],
|
||||
Code: &[]int{http.StatusLocked}[0]
|
||||
})
|
||||
}
|
|
@ -0,0 +1,250 @@
|
|||
package {{ packageName .Path }}
|
||||
|
||||
import (
|
||||
|
||||
"{{ .Project.Name }}/middlewares"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
uuid "github.com/satori/go.uuid"
|
||||
)
|
||||
|
||||
func Init(c *echo.Group) {
|
||||
c.GET("/:id", get)
|
||||
c.POST("", post)
|
||||
c.PUT("/:id", put)
|
||||
c.DELETE("/:id", delete)
|
||||
c.GET("/count", count)
|
||||
c.GET("", list)
|
||||
}
|
||||
|
||||
|
||||
// Get{{ methodNameGetId .Path }}Id get{{ methodNameGetId .Path }}Id
|
||||
// @Summary {{ methodSummary .RestSummary }}
|
||||
// @Description {{ methodComment .RestComment }}
|
||||
// @Tags {{ .RestGroup }}
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "Identificator record"
|
||||
// @Success 200 {object} {{ getModelName .ModelName }}
|
||||
// @Failure 400 {object} structs.Result
|
||||
// @Failure 401 {object} structs.Result
|
||||
// @Failure 404 {object} structs.Result
|
||||
// @Failure 500 {object} structs.Result
|
||||
// @Router /{{ .RestPath }}/{id} [get]
|
||||
// @Security BearerAuth
|
||||
func get(c echo.Context) error {
|
||||
id := uuid.FromStringOrNil(c.Param("id"))
|
||||
|
||||
var err error
|
||||
|
||||
user := c.Get("user").(*jwt.Token)
|
||||
claims := user.Claims.(*structs.JwtCustomClaims)
|
||||
userID := claims.ID
|
||||
|
||||
if !middlewares.InsRole(userID, []string{
|
||||
{{ range $index, $field := .Roles }}
|
||||
// TODO список ролей, которым открыт доступ
|
||||
{{ end }}
|
||||
}) {
|
||||
return c.JSON(http.StatusForbidden, structs.Result{
|
||||
Result: &[]bool{false}[0],
|
||||
Code: &[]int{http.StatusForbidden}[0],
|
||||
Message: &[]string{"Отказано в доступе"}[0],
|
||||
})
|
||||
}
|
||||
|
||||
return restGet(c)
|
||||
|
||||
}
|
||||
|
||||
// {{ displayMethodNamePost .Path }} {{ methodNamePost .Path }}
|
||||
// @Summary {{ methodSummary .RestSummary }}
|
||||
// @Description {{ methodComment .RestComment }}
|
||||
// @Tags {{ .RestGroup }}
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "Identificator record"
|
||||
// @Param body body {{ getModelName .ModelName }} true "Structure for request"
|
||||
// @Success 200 {object} structs.Result
|
||||
// @Failure 400 {object} structs.Result
|
||||
// @Failure 401 {object} structs.Result
|
||||
// @Failure 404 {object} structs.Result
|
||||
// @Failure 500 {object} structs.Result
|
||||
// @Router /{{ .RestPath }} [post]
|
||||
// @Security BearerAuth
|
||||
func post(c echo.Context) error {
|
||||
id := uuid.FromStringOrNil(c.Param("id"))
|
||||
|
||||
var err error
|
||||
|
||||
user := c.Get("user").(*jwt.Token)
|
||||
claims := user.Claims.(*structs.JwtCustomClaims)
|
||||
userID := claims.ID
|
||||
|
||||
if !middlewares.InsRole(userID, []string{
|
||||
{{ range $index, $field := .Roles }}
|
||||
// TODO список ролей, которым открыт доступ
|
||||
{{ end }}
|
||||
}) {
|
||||
return c.JSON(http.StatusForbidden, structs.Result{
|
||||
Result: &[]bool{false}[0],
|
||||
Code: &[]int{http.StatusForbidden}[0],
|
||||
Message: &[]string{"Отказано в доступе"}[0],
|
||||
})
|
||||
}
|
||||
|
||||
return restPost(c)
|
||||
}
|
||||
|
||||
// {{ displayMethodNameGet .RestName }} {{ methodNameGet .RestName }}
|
||||
// @Summary {{ methodSummary .RestSummary }}
|
||||
// @Description {{ methodComment .RestComment }}
|
||||
// @Tags {{ .RestGroup }}
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "Identificator record"
|
||||
// @Param body body {{ getModelName .ModelName }} true "Structure for request"
|
||||
// @Success 200 {object} structs.Result
|
||||
// @Failure 400 {object} structs.Result
|
||||
// @Failure 401 {object} structs.Result
|
||||
// @Failure 404 {object} structs.Result
|
||||
// @Failure 500 {object} structs.Result
|
||||
// @Router /{{ .RestPath }}/{id} [put]
|
||||
// @Security BearerAuth
|
||||
func put(c echo.Context) error {
|
||||
id := uuid.FromStringOrNil(c.Param("id"))
|
||||
|
||||
var err error
|
||||
|
||||
user := c.Get("user").(*jwt.Token)
|
||||
claims := user.Claims.(*structs.JwtCustomClaims)
|
||||
userID := claims.ID
|
||||
|
||||
if !middlewares.InsRole(userID, []string{
|
||||
{{ range $index, $field := .Roles }}
|
||||
// TODO список ролей, которым открыт доступ
|
||||
{{ end }}
|
||||
}) {
|
||||
return c.JSON(http.StatusForbidden, structs.Result{
|
||||
Result: &[]bool{false}[0],
|
||||
Code: &[]int{http.StatusForbidden}[0],
|
||||
Message: &[]string{"Отказано в доступе"}[0],
|
||||
})
|
||||
}
|
||||
|
||||
return restPut(c)
|
||||
}
|
||||
|
||||
// {{ displayMethodNameGet .RestName }} {{ methodNameGet .RestName }}
|
||||
// @Summary {{ methodSummary .RestSummary }}
|
||||
// @Description {{ methodComment .RestComment }}
|
||||
// @Tags {{ .RestGroup }}
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "Identificator record"
|
||||
// @Success 200 {object} structs.Result
|
||||
// @Failure 400 {object} structs.Result
|
||||
// @Failure 401 {object} structs.Result
|
||||
// @Failure 404 {object} structs.Result
|
||||
// @Failure 500 {object} structs.Result
|
||||
// @Router /{{ .RestPath }}/{id} [delete]
|
||||
// @Security BearerAuth
|
||||
func delete(c echo.Context) error {
|
||||
id := uuid.FromStringOrNil(c.Param("id"))
|
||||
|
||||
var err error
|
||||
|
||||
user := c.Get("user").(*jwt.Token)
|
||||
claims := user.Claims.(*structs.JwtCustomClaims)
|
||||
userID := claims.ID
|
||||
|
||||
if !middlewares.InsRole(userID, []string{
|
||||
{{ range $index, $field := .Roles }}
|
||||
// TODO список ролей, которым открыт доступ
|
||||
{{ end }}
|
||||
}) {
|
||||
return c.JSON(http.StatusForbidden, structs.Result{
|
||||
Result: &[]bool{false}[0],
|
||||
Code: &[]int{http.StatusForbidden}[0],
|
||||
Message: &[]string{"Отказано в доступе"}[0],
|
||||
})
|
||||
}
|
||||
|
||||
return restDelete(c)
|
||||
}
|
||||
|
||||
// {{ displayMethodNameGet .RestName }} {{ methodNameGet .RestName }}
|
||||
// @Summary {{ methodSummary .RestSummary }}
|
||||
// @Description {{ methodComment .RestComment }}
|
||||
// @Tags {{ .RestGroup }}
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "Identificator record"
|
||||
// @Success 200 {object} []{{ getModelName .ModelName }}
|
||||
// @Failure 400 {object} structs.Result
|
||||
// @Failure 401 {object} structs.Result
|
||||
// @Failure 404 {object} structs.Result
|
||||
// @Failure 500 {object} structs.Result
|
||||
// @Router /{{ .RestPath }} [get]
|
||||
// @Security BearerAuth
|
||||
func list(c echo.Context) error {
|
||||
id := uuid.FromStringOrNil(c.Param("id"))
|
||||
|
||||
var err error
|
||||
|
||||
user := c.Get("user").(*jwt.Token)
|
||||
claims := user.Claims.(*structs.JwtCustomClaims)
|
||||
userID := claims.ID
|
||||
|
||||
if !middlewares.InsRole(userID, []string{
|
||||
{{ range $index, $field := .Roles }}
|
||||
// TODO список ролей, которым открыт доступ
|
||||
{{ end }}
|
||||
}) {
|
||||
return c.JSON(http.StatusForbidden, structs.Result{
|
||||
Result: &[]bool{false}[0],
|
||||
Code: &[]int{http.StatusForbidden}[0],
|
||||
Message: &[]string{"Отказано в доступе"}[0],
|
||||
})
|
||||
}
|
||||
|
||||
return restList(c)
|
||||
}
|
||||
|
||||
// {{ displayMethodNameGet .RestName }} {{ methodNameGet .RestName }}
|
||||
// @Summary {{ methodSummary .RestSummary }}
|
||||
// @Description {{ methodComment .RestComment }}
|
||||
// @Tags {{ .RestGroup }}
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "Identificator recordя"
|
||||
// @Success 200 {object} int
|
||||
// @Failure 400 {object} structs.Result
|
||||
// @Failure 401 {object} structs.Result
|
||||
// @Failure 404 {object} structs.Result
|
||||
// @Failure 500 {object} structs.Result
|
||||
// @Router /{{ .RestPath }}/count [get]
|
||||
// @Security BearerAuth
|
||||
func count(c echo.Context) error {
|
||||
id := uuid.FromStringOrNil(c.Param("id"))
|
||||
|
||||
var err error
|
||||
|
||||
user := c.Get("user").(*jwt.Token)
|
||||
claims := user.Claims.(*structs.JwtCustomClaims)
|
||||
userID := claims.ID
|
||||
|
||||
if !middlewares.InsRole(userID, []string{
|
||||
{{ range $index, $field := .Roles }}
|
||||
// TODO список ролей, которым открыт доступ
|
||||
{{ end }}
|
||||
}) {
|
||||
return c.JSON(http.StatusForbidden, structs.Result{
|
||||
Result: &[]bool{false}[0],
|
||||
Code: &[]int{http.StatusForbidden}[0],
|
||||
Message: &[]string{"Отказано в доступе"}[0],
|
||||
})
|
||||
}
|
||||
|
||||
return restCount(c)
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package {{ .Name }}
|
||||
|
||||
import "github.com/labstack/echo/v4"
|
||||
|
||||
func restList(c echo.Context) error {
|
||||
return c.JSON(http.StatusLocked, structs.Result{
|
||||
Result: &[]bool{false}[0],
|
||||
Code: &[]int{http.StatusLocked}[0]
|
||||
})
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package {{ .Name }}
|
||||
|
||||
import "github.com/labstack/echo/v4"
|
||||
|
||||
func restPost(c echo.Context) error {
|
||||
return c.JSON(http.StatusLocked, structs.Result{
|
||||
Result: &[]bool{false}[0],
|
||||
Code: &[]int{http.StatusLocked}[0]
|
||||
})
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package {{ .Name }}
|
||||
|
||||
import "github.com/labstack/echo/v4"
|
||||
|
||||
func restPut(c echo.Context) error {
|
||||
return c.JSON(http.StatusLocked, structs.Result{
|
||||
Result: &[]bool{false}[0],
|
||||
Code: &[]int{http.StatusLocked}[0]
|
||||
})
|
||||
}
|
|
@ -0,0 +1,127 @@
|
|||
package {{ .Name }}
|
||||
|
||||
import (
|
||||
"{{ .Name }}/structs"
|
||||
"database/sql"
|
||||
"strconv"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func prepareFilters(tx *gorm.DB, filter *structs.FilterRequest) *gorm.DB {
|
||||
/*var err error
|
||||
if filter.Rows == nil {
|
||||
tx = tx.Limit(3000)
|
||||
} else {
|
||||
tx = tx.Limit(*filter.Rows)
|
||||
}
|
||||
|
||||
if filter.Filter != nil {
|
||||
filterStr := *filter.Filter + "%"
|
||||
var filterFloat64 float64
|
||||
var filterFloat32 *float32
|
||||
var filterInt int64
|
||||
var filterInt64 *int64
|
||||
filterFloat64, err = strconv.ParseFloat(*filter.Filter, 64)
|
||||
if err == nil {
|
||||
filterFloat32 = &[]float32{float32(filterFloat64)}[0]
|
||||
}
|
||||
filterInt, err = strconv.ParseInt(*filter.Filter, 10, 64)
|
||||
if err == nil {
|
||||
filterInt64 = &[]int64{filterInt}[0]
|
||||
}
|
||||
tx = tx.Where(`genus LIKE @filterStr
|
||||
OR "TypeOfMicroorganism"."name" LIKE @filterStr
|
||||
OR strain LIKE @filterStr
|
||||
OR speciesbiovar LIKE @filterStr
|
||||
OR location1 LIKE @filterStr
|
||||
OR location2 LIKE @filterStr
|
||||
|
||||
OR lon = @filterFloat32
|
||||
OR lat = @filterFloat32
|
||||
OR alloc_year = @filterInt`,
|
||||
sql.Named("filterStr", filterStr),
|
||||
sql.Named("filterFloat32", filterFloat32),
|
||||
sql.Named("filterInt", filterInt64),
|
||||
)
|
||||
}
|
||||
|
||||
if filter.SortField != nil {
|
||||
switch *filter.SortField {
|
||||
case "genus":
|
||||
if *filter.SortOrder == 1 {
|
||||
tx = tx.Order("genus ASC")
|
||||
} else {
|
||||
tx = tx.Order("genus DESC")
|
||||
}
|
||||
case "typeOfMicroorganism.name":
|
||||
if *filter.SortOrder == 1 {
|
||||
tx = tx.Order(`"TypeOfMicroorganism"."name" ASC`)
|
||||
} else {
|
||||
tx = tx.Order(`"TypeOfMicroorganism"."name" DESC`)
|
||||
}
|
||||
case "key":
|
||||
if *filter.SortOrder == 1 {
|
||||
tx = tx.Order("key ASC")
|
||||
} else {
|
||||
tx = tx.Order("key DESC")
|
||||
}
|
||||
case "strain":
|
||||
if *filter.SortOrder == 1 {
|
||||
tx = tx.Order("strain ASC")
|
||||
} else {
|
||||
tx = tx.Order("strain DESC")
|
||||
}
|
||||
case "speciesbiovar":
|
||||
if *filter.SortOrder == 1 {
|
||||
tx = tx.Order("speciesbiovar ASC")
|
||||
} else {
|
||||
tx = tx.Order("speciesbiovar DESC")
|
||||
}
|
||||
case "location1":
|
||||
if *filter.SortOrder == 1 {
|
||||
tx = tx.Order("location1 ASC")
|
||||
} else {
|
||||
tx = tx.Order("location1 DESC")
|
||||
}
|
||||
case "location2":
|
||||
if *filter.SortOrder == 1 {
|
||||
tx = tx.Order("location2 ASC")
|
||||
} else {
|
||||
tx = tx.Order("location2 DESC")
|
||||
}
|
||||
case "year":
|
||||
if *filter.SortOrder == 1 {
|
||||
tx = tx.Order("year ASC")
|
||||
} else {
|
||||
tx = tx.Order("year DESC")
|
||||
}
|
||||
case "lat":
|
||||
if *filter.SortOrder == 1 {
|
||||
tx = tx.Order("lat ASC")
|
||||
} else {
|
||||
tx = tx.Order("lat DESC")
|
||||
}
|
||||
case "lon":
|
||||
if *filter.SortOrder == 1 {
|
||||
tx = tx.Order("lon ASC")
|
||||
} else {
|
||||
tx = tx.Order("lon DESC")
|
||||
}
|
||||
case "allocYear":
|
||||
if *filter.SortOrder == 1 {
|
||||
tx = tx.Order("alloc_year ASC")
|
||||
} else {
|
||||
tx = tx.Order("alloc_year DESC")
|
||||
}
|
||||
case "allocDate":
|
||||
if *filter.SortOrder == 1 {
|
||||
tx = tx.Order("alloc_date ASC")
|
||||
} else {
|
||||
tx = tx.Order("alloc_date DESC")
|
||||
}
|
||||
}
|
||||
}
|
||||
return tx*/
|
||||
return nil
|
||||
}
|
|
@ -20,12 +20,14 @@ type VisField struct {
|
|||
}
|
||||
|
||||
type Rest struct {
|
||||
Name string `yam:"name,omitempty" json:"name,omitempty" default:"noname"` // Имя раздела запросов
|
||||
GroupName string `yaml:"groupName,omitempty" json:"groupName,omitempty" default:"nogroup"` // Имя группы, в которую входит данный путь REST
|
||||
Data VisField `yaml:"data,omitempty" json:"data,omitempty"` // Модель данных, на основе которой строиться запрос
|
||||
Edit []VisField `yaml:"edits,omitempty" json:"edits,omitempty"` // Список полей для редактирования
|
||||
Visible []VisField `yaml:"visible,omitempty" json:"visible,omitempty"` // Список видимых полей. Если указан хоть один, то отображаются только те, которые указаны, иначе отображаются все
|
||||
Invisible []VisField `yaml:"invisible,omitempty" json:"invisible,omitempty"` // Список невидимых полей. Если указан хоть один, то отображаются все кроме указанного, иначе берется правило из поля "visible". Является приоритетным и в данном случае поле "visible" игнорируется
|
||||
Filter []VisField `yaml:"filter,omitempty" json:"filter,omitempty"` // Указывается список полей, по которым будет осуществляться поиск
|
||||
Editable bool `yaml:"editable,omitempty" json:"editable,omitempty"` // Модель является редактируемой, т.е. необходимо сгенерировать rest для данной модели. Для данного пути будут сформированы методы GET, POST, PUT и DELETE с соответствующим путем /<path>/{id}
|
||||
FieldID VisField `yaml:"fieldId,omitempty" json:"fieldId,omitempty"` // Поле, которое является ключевым при работе с конкретной записью
|
||||
FieldID VisField `yaml:"fieldId,omitempty" json:"fieldId,omitempty"` // Поле, которое является ключевым при работе с конкретной записью. Если модель данных указана db, то ключевое поле берется из описания БД и игнорируется.
|
||||
Roles map[string][]string `yaml:"roles,omitempty" json:"roles,omitempty"` // Список ролей, которым разрешено работать с данным. Операция: массив строк с названием ролей. Если не указано, то все роли. Операция для просмотра списка: LIST
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue