80 lines
1.8 KiB
Go
80 lines
1.8 KiB
Go
package seeds
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
|
|
"github.com/Caknoooo/go-gin-clean-starter/database/entities"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type RoleSeed struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Description string `json:"description"`
|
|
IconUrl string `json:"icon_url"`
|
|
Type string `json:"type"`
|
|
HomeUrl string `json:"home_url"`
|
|
ClientName string `json:"client_name"`
|
|
}
|
|
|
|
func ListRoleSeeder(db *gorm.DB) error {
|
|
jsonFile, err := os.Open("./database/seeders/json/roles.json")
|
|
if err != nil {
|
|
fmt.Println("Error opening file:", err)
|
|
return err
|
|
}
|
|
|
|
jsonData, err := io.ReadAll(jsonFile)
|
|
if err != nil {
|
|
fmt.Println("Error reading file:", err)
|
|
return err
|
|
}
|
|
|
|
var listRole []RoleSeed
|
|
if err := json.Unmarshal(jsonData, &listRole); err != nil {
|
|
fmt.Println("Error unmarshalling JSON:", err)
|
|
return err
|
|
}
|
|
|
|
hasTable := db.Migrator().HasTable(&entities.M_Role{})
|
|
if !hasTable {
|
|
fmt.Println("Creating table: M_Role")
|
|
if err := db.Migrator().CreateTable(&entities.M_Role{}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
for _, data := range listRole {
|
|
var role entities.M_Role
|
|
var client entities.M_Client
|
|
|
|
if err := db.Where("name = ?", data.ClientName).First(&client).Error; err != nil {
|
|
fmt.Println("Client not found:", err)
|
|
return err // client tidak ditemukan
|
|
}
|
|
|
|
// err := db.Where(&entities.M_Role{Name: data.Name}).First(&role).Error
|
|
// if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
// fmt.Println("Error querying role:", err)
|
|
// return err
|
|
// }
|
|
|
|
if err := db.FirstOrCreate(&role, entities.M_Role{
|
|
Name: data.Name,
|
|
Description: data.Description,
|
|
IconUrl: data.IconUrl,
|
|
Type: data.Type,
|
|
HomeUrl: data.HomeUrl,
|
|
ClientID: client.ID,
|
|
}).Error; err != nil {
|
|
fmt.Println("Error seeding role:", err)
|
|
return err
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|