聊聊go.cqrs的DomainRepository

本文主要研究一下go.cqrs的DomainRepository

DomainRepository

// DomainRepository is the interface that all domain repositories should implement.
type DomainRepository interface {
    //Loads an aggregate of the given type and ID
    Load(aggregateTypeName string, aggregateID string) (AggregateRoot, error)

    //Saves the aggregate.
    Save(aggregate AggregateRoot, expectedVersion *int) error
}
DomainRepository定义了Load、Save方法

GetEventStoreCommonDomainRepo

// GetEventStoreCommonDomainRepo is an implementation of the DomainRepository
// that uses GetEventStore for persistence
type GetEventStoreCommonDomainRepo struct {
    eventStore         *goes.Client
    eventBus           EventBus
    streamNameDelegate StreamNamer
    aggregateFactory   AggregateFactory
    eventFactory       EventFactory
}

// Load will load all events from a stream and apply those events to an aggregate
// of the type specified.
//
// The aggregate type and id will be passed to the configured StreamNamer to
// get the stream name.
func (r *GetEventStoreCommonDomainRepo) Load(aggregateType, id string) (AggregateRoot, error) {

    if r.aggregateFactory == nil {
        return nil, fmt.Errorf("The common domain repository has no Aggregate Factory.")
    }

    if r.streamNameDelegate == nil {
        return nil, fmt.Errorf("The common domain repository has no stream name delegate.")
    }

    if r.eventFactory == nil {
        return nil, fmt.Errorf("The common domain has no Event Factory.")
    }

    aggregate := r.aggregateFactory.GetAggregate(aggregateType, id)
    if aggregate == nil {
        return nil, fmt.Errorf("The repository has no aggregate factory registered for aggregate type: %s", aggregateType)
    }

    streamName, err := r.streamNameDelegate.GetStreamName(aggregateType, id)
    if err != nil {
        return nil, err
    }

    stream := r.eventStore.NewStreamReader(streamName)
    for stream.Next() {
        switch err := stream.Err().(type) {
        case nil:
            break
        case *url.Error, *goes.ErrTemporarilyUnavailable:
            return nil, &ErrRepositoryUnavailable{}
        case *goes.ErrNoMoreEvents:
            return aggregate, nil
        case *goes.ErrUnauthorized:
            return nil, &ErrUnauthorized{}
        case *goes.ErrNotFound:
            return nil, &ErrAggregateNotFound{AggregateType: aggregateType, AggregateID: id}
        default:
            return nil, &ErrUnexpected{Err: err}
        }

        event := r.eventFactory.GetEvent(stream.EventResponse().Event.EventType)

        //TODO: No test for meta
        meta := make(map[string]string)
        stream.Scan(event, &meta)
        if stream.Err() != nil {
            return nil, stream.Err()
        }
        em := NewEventMessage(id, event, Int(stream.EventResponse().Event.EventNumber))
        for k, v := range meta {
            em.SetHeader(k, v)
        }
        aggregate.Apply(em, false)
        aggregate.IncrementVersion()
    }

    return aggregate, nil

}

// Save persists an aggregate
func (r *GetEventStoreCommonDomainRepo) Save(aggregate AggregateRoot, expectedVersion *int) error {

    if r.streamNameDelegate == nil {
        return fmt.Errorf("The common domain repository has no stream name delagate.")
    }

    resultEvents := aggregate.GetChanges()

    streamName, err := r.streamNameDelegate.GetStreamName(typeOf(aggregate), aggregate.AggregateID())
    if err != nil {
        return err
    }

    if len(resultEvents) > 0 {

        evs := make([]*goes.Event, len(resultEvents))

        for k, v := range resultEvents {
            //TODO: There is no test for this code
            v.SetHeader("AggregateID", aggregate.AggregateID())
            evs[k] = goes.NewEvent("", v.EventType(), v.Event(), v.GetHeaders())
        }

        streamWriter := r.eventStore.NewStreamWriter(streamName)
        err := streamWriter.Append(expectedVersion, evs...)
        switch e := err.(type) {
        case nil:
            break
        case *goes.ErrConcurrencyViolation:
            return &ErrConcurrencyViolation{Aggregate: aggregate, ExpectedVersion: expectedVersion, StreamName: streamName}
        case *goes.ErrUnauthorized:
            return &ErrUnauthorized{}
        case *goes.ErrTemporarilyUnavailable:
            return &ErrRepositoryUnavailable{}
        default:
            return &ErrUnexpected{Err: e}
        }
    }

    aggregate.ClearChanges()

    for k, v := range resultEvents {
        if expectedVersion == nil {
            r.eventBus.PublishEvent(v)
        } else {
            em := NewEventMessage(v.AggregateID(), v.Event(), Int(*expectedVersion+k+1))
            r.eventBus.PublishEvent(em)
        }
    }

    return nil
}
GetEventStoreCommonDomainRepo定义了eventStore、eventBus、streamNameDelegate、aggregateFactory、eventFactory属性,其Load方法先通过r.aggregateFactory.GetAggregate获取aggregate,再通过r.streamNameDelegate.GetStreamName(aggregateType, id)获取streamName,然后通过r.eventStore.NewStreamReader去遍历event,挨个执行aggregate.Apply(em, false)及aggregate.IncrementVersion();其Save方法先通过aggregate.GetChanges()获取resultEvents,再遍历resultEvents构造goes.Event,之后通过streamWriter.Append写入,然后执行aggregate.ClearChanges(),最后执行r.eventBus.PublishEvent

小结

go.cqrs的DomainRepository定义了Load、Save方法;GetEventStoreCommonDomainRepo实现了DomainRepository接口,其Load方法主要是读取event,然后挨个执行aggregate.Apply;其Save方法主要是将aggregate.GetChanges()转换为event,然后通过streamWriter.Append写入,然后执行aggregate.ClearChanges(),最后执行r.eventBus.PublishEvent。

doc


code-craft
spring boot , docker and so on 欢迎关注微信公众号: geek_luandun

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很...

11.8k 声望
2k 粉丝
0 条评论
推荐阅读
2022年终总结
最近两年开始陷入颓废中,博客也写的越来越少了。究其原因,主要还是陷入了职业倦怠期,最近一次跳槽感觉颇为失败,但是碍于给的薪资高,为了五斗米折腰,又加上最近行情不好,想要往外跳也跳不了,就这样子一直...

codecraft阅读 724

Golang 中 []byte 与 string 转换
string 类型和 []byte 类型是我们编程时最常使用到的数据结构。本文将探讨两者之间的转换方式,通过分析它们之间的内在联系来拨开迷雾。

机器铃砍菜刀22阅读 55.2k评论 1

年度最佳【golang】map详解
这篇文章主要讲 map 的赋值、删除、查询、扩容的具体执行过程,仍然是从底层的角度展开。结合源码,看完本文一定会彻底明白 map 底层原理。

去去100214阅读 11.1k评论 2

年度最佳【golang】GMP调度详解
Golang最大的特色可以说是协程(goroutine)了, 协程让本来很复杂的异步编程变得简单, 让程序员不再需要面对回调地狱, 虽然现在引入了协程的语言越来越多, 但go中的协程仍然是实现的是最彻底的. 这篇文章将通过分析...

去去100213阅读 11.3k评论 4

【已结束】SegmentFault 思否技术征文丨浅谈 Go 语言框架
亲爱的开发者们:我们的 11 月技术征文如期而来,这次主题围绕 「 Go 」 语言,欢迎大家来参与分享~征文时间11 月 4 日 - 11 月 27 日 23:5911 月 28 日 18:00 前发布中奖名单参与条件新老思否作者均可参加征文...

SegmentFault思否11阅读 4.7k评论 11

封面图
【Go微服务】开发gRPC总共分三步
之前我也有写过RPC相关的文章:《 Go RPC入门指南:RPC的使用边界在哪里?如何实现跨语言调用?》,详细介绍了RPC是什么,使用边界在哪里?并且用Go和php举例,实现了跨语言调用。不了解RPC的同学建议先读这篇文...

王中阳Go8阅读 3.7k评论 6

封面图
【golang】sync.WaitGroup详解
上一期中,我们介绍了 sync.Once 如何保障 exactly once 语义,本期文章我们介绍 package sync 下的另一个工具类:sync.WaitGroup。

去去100213阅读 30.2k评论 2

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很...

11.8k 声望
2k 粉丝
宣传栏