package rest

import (
	"context"
	"git.nspix.com/golang/micro/gateway/http"
	"git.nspix.com/golang/rest/crud"
	"git.nspix.com/golang/rest/orm/schema"
	"gorm.io/gorm"
	"sync"
)

var (
	once sync.Once
)

func Initialize(hs *http.Server, db *gorm.DB) {
	var err error
	once.Do(func() {
		if err = schema.Initialize(context.Background(), db, hs); err != nil {
			return
		}
		crud.Default.SetDB(db)
		crud.Default.SetHttpServer(hs)
	})
}

//register model instance
func RegisterModel(module string, value interface{}, opts ...crud.Option) (err error) {
	if err = schema.Migrate(module, crud.Default.GetDB(), value); err == nil {
		crud.Default.Register(module, value, opts...)
	}
	return
}
