feat: crudgen

This commit is contained in:
2025-01-06 00:09:51 +07:00
parent 8c2f415e80
commit 7b2afbcc46
17 changed files with 728 additions and 23 deletions

View File

@@ -0,0 +1,45 @@
package services
import (
"app/internal/dal"
"app/internal/models"
"errors"
"gorm.io/gen/field"
"gorm.io/gorm"
)
type AuthorService struct{}
type Author = models.Author
func (service *AuthorService) Create(item Author) (Author, error) {
err := dal.Author.Preload(field.Associations).Create(&item)
return item, err
}
func (service *AuthorService) GetAll() ([]*Author, error) {
var authors []*Author
authors, err := dal.Author.Preload(field.Associations).Find()
return authors, err
}
func (service *AuthorService) GetById(id uint) (*Author, error) {
item, err := dal.Author.Preload(field.Associations).Where(dal.Author.Id.Eq(id)).First()
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
} else {
return nil, err
}
}
return item, nil
}
func (service *AuthorService) Update(item Author) (Author, error) {
err := dal.Author.Preload(field.Associations).Save(&item)
return item, err
}
func (service *AuthorService) Delete(item Author) (Author, error) {
_, err := dal.Author.Unscoped().Preload(field.Associations).Delete(&item)
return item, err
}
func (service *AuthorService) Count() (int64, error) {
amount, err := dal.Author.Count()
return amount, err
}

View File

@@ -7,6 +7,7 @@ import (
func InsertDefaultData() {
insertPosts()
insertAuthors()
}
func InsertDefaultEntityData[T any](service Service[T], entities []T) {
@@ -34,3 +35,12 @@ func insertPosts() {
},
})
}
func insertAuthors() {
InsertDefaultEntityData(&AuthorService{}, []Author{
{
Id: 1,
Name: "ИА Кузбасс",
},
})
}

View File

@@ -15,13 +15,11 @@ func (service *PostService) Create(item Post) (Post, error) {
err := dal.Post.Preload(field.Associations).Create(&item)
return item, err
}
func (service *PostService) GetAll() ([]*Post, error) {
var posts []*Post
posts, err := dal.Post.Preload(field.Associations).Find()
return posts, err
}
func (service *PostService) GetById(id uint) (*Post, error) {
item, err := dal.Post.Preload(field.Associations).Where(dal.Post.Id.Eq(id)).First()
if err != nil {
@@ -31,20 +29,16 @@ func (service *PostService) GetById(id uint) (*Post, error) {
return nil, err
}
}
return item, nil
}
func (service *PostService) Update(item Post) (Post, error) {
err := dal.Post.Preload(field.Associations).Save(&item)
return item, err
}
func (service *PostService) Delete(item Post) (Post, error) {
_, err := dal.Post.Unscoped().Preload(field.Associations).Delete(&item)
return item, err
}
func (service *PostService) Count() (int64, error) {
amount, err := dal.Post.Count()
return amount, err

View File

@@ -4,4 +4,5 @@ import "github.com/wailsapp/wails/v3/pkg/application"
var ExportedServices = []application.Service{
application.NewService(&PostService{}),
application.NewService(&AuthorService{}),
}