aboutsummaryrefslogtreecommitdiffstats
path: root/entity/merge.go
blob: 1b68b4de284dc8a1952c46e946861a87fc6bfdc7 (plain) (blame)
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package entity

import (
	"fmt"
)

// MergeStatus represent the result of a merge operation of an entity
type MergeStatus int

const (
	_                  MergeStatus = iota
	MergeStatusNew                 // a new Entity was created locally
	MergeStatusInvalid             // the remote data is invalid
	MergeStatusUpdated             // a local Entity has been updated
	MergeStatusNothing             // no changes were made to a local Entity (already up to date)
	MergeStatusError               // a terminal error happened
)

// MergeResult hold the result of a merge operation on an Entity.
type MergeResult struct {
	// Err is set when a terminal error occur in the process
	Err error

	Id     Id
	Status MergeStatus

	// Only set for Invalid status
	Reason string

	// Only set for New or Updated status
	Entity Interface
}

func (mr MergeResult) String() string {
	switch mr.Status {
	case MergeStatusNew:
		return "new"
	case MergeStatusInvalid:
		return fmt.Sprintf("invalid data: %s", mr.Reason)
	case MergeStatusUpdated:
		return "updated"
	case MergeStatusNothing:
		return "nothing to do"
	case MergeStatusError:
		return fmt.Sprintf("merge error on %s: %s", mr.Id, mr.Err.Error())
	default:
		panic("unknown merge status")
	}
}

// TODO: Interface --> *Entity ?
func NewMergeNewStatus(id Id, entity Interface) MergeResult {
	return MergeResult{
		Id:     id,
		Status: MergeStatusNew,
		Entity: entity,
	}
}

func NewMergeInvalidStatus(id Id, reason string) MergeResult {
	return MergeResult{
		Id:     id,
		Status: MergeStatusInvalid,
		Reason: reason,
	}
}

func NewMergeUpdatedStatus(id Id, entity Interface) MergeResult {
	return MergeResult{
		Id:     id,
		Status: MergeStatusUpdated,
		Entity: entity,
	}
}

func NewMergeNothingStatus(id Id) MergeResult {
	return MergeResult{
		Id:     id,
		Status: MergeStatusNothing,
	}
}

func NewMergeError(err error, id Id) MergeResult {
	return MergeResult{
		Id:     id,
		Status: MergeStatusError,
		Err:    err,
	}
}