event.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package store
  2. const (
  3. Get = "get"
  4. Create = "create"
  5. Set = "set"
  6. Update = "update"
  7. Delete = "delete"
  8. CompareAndSwap = "compareAndSwap"
  9. Expire = "expire"
  10. )
  11. type Event struct {
  12. Action string `json:"action"`
  13. Node *NodeExtern `json:"node,omitempty"`
  14. }
  15. func newEvent(action string, key string, modifiedIndex, createdIndex uint64) *Event {
  16. n := &NodeExtern{
  17. Key: key,
  18. ModifiedIndex: modifiedIndex,
  19. CreatedIndex: createdIndex,
  20. }
  21. return &Event{
  22. Action: action,
  23. Node: n,
  24. }
  25. }
  26. func (e *Event) IsCreated() bool {
  27. if e.Action == Create {
  28. return true
  29. }
  30. if e.Action == Set && e.Node.PrevValue == "" {
  31. return true
  32. }
  33. return false
  34. }
  35. func (e *Event) Index() uint64 {
  36. return e.Node.ModifiedIndex
  37. }
  38. // Converts an event object into a response object.
  39. func (event *Event) Response() interface{} {
  40. if !event.Node.Dir {
  41. response := &Response{
  42. Action: event.Action,
  43. Key: event.Node.Key,
  44. Value: event.Node.Value,
  45. PrevValue: event.Node.PrevValue,
  46. Index: event.Node.ModifiedIndex,
  47. TTL: event.Node.TTL,
  48. Expiration: event.Node.Expiration,
  49. }
  50. if response.Action == Set {
  51. if response.PrevValue == "" {
  52. response.NewKey = true
  53. }
  54. }
  55. if response.Action == CompareAndSwap || response.Action == Create {
  56. response.Action = "testAndSet"
  57. }
  58. return response
  59. } else {
  60. responses := make([]*Response, len(event.Node.Nodes))
  61. for i, node := range event.Node.Nodes {
  62. responses[i] = &Response{
  63. Action: event.Action,
  64. Key: node.Key,
  65. Value: node.Value,
  66. Dir: node.Dir,
  67. Index: node.ModifiedIndex,
  68. }
  69. }
  70. return responses
  71. }
  72. }