MCPcopy Create free account
hub / github.com/ByteStorage/FlyDB / XAdd

Method XAdd

structure/stream.go:98–171  ·  view source on GitHub ↗

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{})

Source from the content-addressed store, hash-verified

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.
98func (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

Callers 7

TestStreamStructure_XDelFunction · 0.80
TestStreamStructure_XLenFunction · 0.80

Calls 4

encodeStreamsMethod · 0.95
decodeStreamsMethod · 0.95
GetMethod · 0.65
PutMethod · 0.65

Tested by 7

TestStreamStructure_XDelFunction · 0.64
TestStreamStructure_XLenFunction · 0.64