zahir-core / grest

An instant, full-featured, and scalable REST APIs framework for Go. Designed to make rapid development easy with clean code and best performance.
MIT License
13 stars 1 forks source link

seeder #34

Closed lismansihotang closed 2 months ago

lismansihotang commented 4 months ago

bagaimana menggaktifkan seeder ketika pertama kali migrator berjalan?thanks

jeffry-luqman commented 2 months ago

apabila asumsi nya single db (bukan multi tenant), maka contoh nya sebagai berikut :

  1. buat function seeder nya misalnya sebagai berikut
    
    // src/currencies/currency.seeder.go
    package currencies

import "gorm.io/gorm"

func Seeder(tx *gorm.DB) error { for _, d := range []struct { Code string Name string Symbol string Unit string Fraction string }{ // other data {"EUR", "Euro", "€", "Euro", "Cent"}, {"IDR", "Indonesian rupiah", "Rp", "Rupiah", "Sen"}, {"LYD", "Libyan dinar", "ل.د", "Dinar", "Dirham"}, {"SAR", "Saudi riyal", "ر.س", "Riyal", "Halala"}, {"USD", "United States dollar", "$", "Dollar", "Cent"}, // other data } { c := Currency{} c.Code.Set(d.Code) c.Name.Set(d.Name) c.Symbol.Set(d.Symbol) c.Unit.Set(d.Unit) c.Fraction.Set(d.Fraction) old := Currency{} tx.Where("code = ?", d.Code).Take(&old) if old.Code.String != "" { tx.Where("code = ?", old.Code.String).Updates(&c) } else { tx.Create(&c) } } return nil }

2. daftarkan seeder tersebut pada file src/seeder.go misalnya sebagai berikut
```go
package src

import (
  "github.com/foo/bar/app"
  "github.com/foo/bar/src/currency"
)

func Seeder() *seederUtil {
  if seeder == nil {
    seeder = &seederUtil{}
    seeder.Configure()
    if app.APP_ENV == "local" || app.IS_MAIN_SERVER {
      seeder.Run()
    }
    seeder.isConfigured = true
  }
  return seeder
}

var seeder *seederUtil

type seederUtil struct {
  isConfigured bool
}

func (s *seederUtil) Configure() {
  app.DB().RegisterSeeder("main", "2024-09-05_13.54-currencies", currency.Seeder)
  // setiap ada penambahan atau update seeder, cukup ditambahkan / diupdate disini
}

func (s *seederUtil) Run() {
  tx, err := app.DB().Conn("main")
  if err == nil {
    err = app.DB().RunSeeder(tx, "main", app.Setting{})
  }
  if err != nil {
    app.Logger().Fatal().Err(err).Send()
  }
}
  1. ketika aplikasi dijalankan, maka setelah proses migrasi selesai dilanjutkan dengan seeder nya