group_leave.go 1.28 KB
Newer Older
chenweijian's avatar
chenweijian committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
package group_ev

import (
	"hilo-user/_const"
	"hilo-user/domain"
	"hilo-user/domain/event"
	"hilo-user/myerr"
	"hilo-user/resource/mysql"
)

var groupLeaveListen = new(event.Base)

// 离房事件
type GroupLeaveEvent struct {
	GroupId    string
	UserId     mysql.ID
	ExternalId string
}

func AddGroupLeaveEventSync(callback func(model *domain.Model, event interface{}) error) {
	groupLeaveListen.SyncList = append(groupLeaveListen.SyncList, callback)
}

func AddGroupLeaveEventAsync(callback func(model *domain.Model, event interface{}) error) {
	groupLeaveListen.AsyncList = append(groupLeaveListen.AsyncList, callback)
}

func PublishGroupLeaveEvent(model *domain.Model, event interface{}) error {
	// 执行同步的领域事件
	for _, callback := range groupLeaveListen.SyncList {
		if err := callback(model, event); err != nil {
			return myerr.WrapErr(err)
		}
	}
	// 执行异步的领域事件
	if len(groupLeaveListen.AsyncList) > 0 {
		go func() {
			defer _const.CheckGoPanic()
			for _, callback := range groupLeaveListen.AsyncList {
				// 异步事件需要用新model,主要是db
				var newModel = domain.CreateModelContext(model.MyContext)
				if err := callback(newModel, event); err != nil {
					model.Log.Errorf("GroupInEvent aysnc fail:%v", err)
				}
			}
		}()
	}
	return nil
}