XAdd adds a new message to a stream. If the stream does not exist, it will be created. If the message ID already exists, it will return false. Parameters: name: The name of the stream. id: The ID of the message. fields: The fields (attributes) of the message. It should be a map[string]
(name, id string, fields map[string]interface{})
| 96 | // - If the message ID already exists in the stream, the function will return false and ErrExistID. |
| 97 | // - Otherwise, the message will be added to the stream, and the stream will be stored in the database. |
| 98 | func (s *StreamStructure) XAdd(name, id string, fields map[string]interface{}) (bool, error) { |
| 99 | // Check if the arguments are valid |
| 100 | if len(id) == 0 || len(fields) == 0 || fields == nil { |
| 101 | return false, ErrInvalidXArgs |
| 102 | } |
| 103 | |
| 104 | // Get the stream |
| 105 | value, _ := s.db.Get([]byte(name)) |
| 106 | if value == nil { |
| 107 | // Create a new stream |
| 108 | s.streams = &Streams{ |
| 109 | Name: name, |
| 110 | Messages: []*StreamMessage{}, |
| 111 | Groups: map[string]*StreamGroup{}, |
| 112 | LastMessage: time.Now(), |
| 113 | } |
| 114 | |
| 115 | // Create a new message |
| 116 | message := &StreamMessage{ |
| 117 | Id: id, |
| 118 | Fields: fields, |
| 119 | } |
| 120 | // Add the message to the stream |
| 121 | s.streams.Messages = append(s.streams.Messages, message) |
| 122 | |
| 123 | // Encode the streams |
| 124 | encodedStreams, err := s.encodeStreams(s.streams) |
| 125 | if err != nil { |
| 126 | return false, err |
| 127 | } |
| 128 | |
| 129 | // Set the stream |
| 130 | if err = s.db.Put([]byte(s.streams.Name), encodedStreams); err != nil { |
| 131 | return false, err |
| 132 | } |
| 133 | |
| 134 | return true, nil |
| 135 | } else { |
| 136 | // Decode the streams |
| 137 | err := s.decodeStreams(value, s.streams) |
| 138 | if err != nil { |
| 139 | return false, err |
| 140 | } |
| 141 | |
| 142 | // Check if the message ID already exists |
| 143 | for _, msg := range s.streams.Messages { |
| 144 | if msg.Id == id { |
| 145 | return false, ErrExistID |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | // Create a new message |
| 150 | message := &StreamMessage{ |
| 151 | Id: id, |
| 152 | Fields: fields, |
| 153 | } |
| 154 | |
| 155 | // Add the message to the stream |