# Appending Events

TIP

Check connecting to EventStoreDB instructions to learn how to configure and use the client SDK.

The simplest way to append an event to EventStoreDB is to create an EventData object and call AppendToStream method.

    var eventData = new EventData(
    	Uuid.NewUuid(),
    	"some-event",
    	Encoding.UTF8.GetBytes("{\"id\": \"1\" \"value\": \"some value\"}")
    );
    
    await client.AppendToStreamAsync(
    	"some-stream",
    	StreamState.NoStream,
    	new List<EventData> {
    		eventData
    	});
    EventData eventData = EventData
            .builderAsJson(
                    UUID.randomUUID(),
                    "some-event",
                    new TestEvent(
                            "1",
                            "some value"
                    ))
            .build();
    
    AppendToStreamOptions options = AppendToStreamOptions.get()
            .expectedRevision(ExpectedRevision.NO_STREAM);
    
    client.appendToStream("some-stream", options, eventData)
            .get();
    const event = jsonEvent({
      id: uuid(),
      type: "some-event",
      data: {
        id: "1",
        value: "some value",
      },
    });
    
    await client.appendToStream("some-stream", event, {
      expectedRevision: NO_STREAM,
    });
    let data = TestEvent {
        id: "1".to_string(),
        important_data: "some value".to_string(),
    };
    
    let event = EventData::json("some-event", &data)?.id(Uuid::new_v4());
    let options = AppendToStreamOptions::default().expected_revision(ExpectedRevision::NoStream);
    
    let _ = client
        .append_to_stream("some-stream", &options, event)
        .await?;
    // Make sure to add code blocks to your code group

    As you can see AppendToStream method allows takes a collection of EventData, which makes possible saving more than one event in a single batch.

    As well as the example above there is also a number of other options for dealing with different scenarios.

    TIP

    If you are new to event sourcing its probably wise to pay special attention to handling concurrency that is detailed below.

    # Working with EventData

    When appending events to EventStoreDB they must first all be wrapped in an EventData object. This allow you to specify the content of the event, the type of event and whether its in Json format. In it's simplest form you need to the three following arguments.

    # eventId

    This takes the format of a Uuid and is used to uniquely identify the event you are trying to append. If two events with the same Uuid are appended to the same stream in quick succession EventStoreDB will only append one copy of the event to the stream.

    For example:

      var eventData = new EventData(
      	Uuid.NewUuid(),
      	"some-event",
      	Encoding.UTF8.GetBytes("{\"id\": \"1\" \"value\": \"some value\"}")
      );
      
      await client.AppendToStreamAsync(
      	"same-event-stream",
      	StreamState.Any,
      	new List<EventData> {
      		eventData
      	});
      
      // attempt to append the same event again
      await client.AppendToStreamAsync(
      	"same-event-stream",
      	StreamState.Any,
      	new List<EventData> {
      		eventData
      	});
      EventData eventData = EventData
              .builderAsJson(
                      UUID.randomUUID(),
                      "some-event",
                      new TestEvent(
                              "1",
                              "some value"
                      ))
              .build();
      
      AppendToStreamOptions options = AppendToStreamOptions.get()
              .expectedRevision(ExpectedRevision.ANY);
      
      client.appendToStream("same-event-stream", options, eventData)
              .get();
      
      // attempt to append the same event again
      client.appendToStream("same-event-stream", options, eventData)
              .get();
      const event = jsonEvent({
        id: uuid(),
        type: "some-event",
        data: {
          id: "1",
          value: "some value",
        },
      });
      
      await client.appendToStream("same-event-stream", event);
      
      // attempt to append the same event again
      await client.appendToStream("same-event-stream", event);
      let data = TestEvent {
          id: "1".to_string(),
          important_data: "some value".to_string(),
      };
      
      let event = EventData::json("some-event", &data)?.id(Uuid::new_v4());
      let options = AppendToStreamOptions::default();
      
      let _ = client
          .append_to_stream("same-event-stream", &options, event.clone())
          .await?;
      
      let _ = client
          .append_to_stream("same-event-stream", &options, event)
          .await?;
      // Make sure to add code blocks to your code group

      will result in only a single event being appended.

      Duplicate Event

      # type

      An event type should be supplied for each event. This is a unique string used to identify the type of event you are saving.

      It is common to see the explicit event code type name used as the type as it makes serialising and de-serialising of the event easy. However we recommend against this as it couples the storage to the type and will make it more difficult if you need to version the event at a later date.

      # data

      Representation of your event data. It is recommended that you store your events as JSON objects as this will allow you to make use of all of EventStoreDB's functionality such as projections. Ultimately though, you can save it using whatever format you like as eventually, it will be stored as encoded bytes.

      # metadata

      It is common to need to store additional information along side your event that is part of the event it's self. This can be correlation Id's, timestamps, access information etc. EventStoreDB allows you to store a separate byte array containing this information to keep it separate.

      # isJson

      Simple boolean field to tell EventStoreDB if the event is stored as json, true by default.

      # Handling concurrency

      When appending events to a stream you can supply a stream state or stream revision. Your client can use this to tell EventStoreDB what state or version you expect the stream to be in when you append. If the stream isn't in that state then an exception will be thrown.

      For example if we try and append the same record twice expecting both times that the stream doesn't exist we will get an exception on the second:

        var eventDataOne = new EventData(
        	Uuid.NewUuid(),
        	"some-event",
        	Encoding.UTF8.GetBytes("{\"id\": \"1\" \"value\": \"some value\"}")
        );
        
        var eventDataTwo = new EventData(
        	Uuid.NewUuid(),
        	"some-event",
        	Encoding.UTF8.GetBytes("{\"id\": \"2\" \"value\": \"some other value\"}")
        );
        
        await client.AppendToStreamAsync(
        	"no-stream-stream",
        	StreamState.NoStream,
        	new List<EventData> {
        		eventDataOne
        	});
        
        // attempt to append the same event again
        await client.AppendToStreamAsync(
        	"no-stream-stream",
        	StreamState.NoStream,
        	new List<EventData> {
        		eventDataTwo
        	});
        EventData eventDataOne = EventData
                .builderAsJson(
                        UUID.randomUUID(),
                        "some-event",
                        new TestEvent(
                                "1",
                                "some value"
                        ))
                .build();
        
        EventData eventDataTwo = EventData
                .builderAsJson(
                        UUID.randomUUID(),
                        "some-event",
                        new TestEvent(
                                "2",
                                "some other value"
                        ))
                .build();
        
        AppendToStreamOptions options = AppendToStreamOptions.get()
                .expectedRevision(ExpectedRevision.NO_STREAM);
        
        client.appendToStream("no-stream-stream", options, eventDataOne)
                .get();
        
        // attempt to append the same event again
        client.appendToStream("no-stream-stream", options, eventDataTwo)
                .get();
        const eventOne = jsonEvent({
          id: uuid(),
          type: "some-event",
          data: {
            id: "1",
            value: "some value",
          },
        });
        
        const eventTwo = jsonEvent({
          id: uuid(),
          type: "some-event",
          data: {
            id: "2",
            value: "some other value",
          },
        });
        
        await client.appendToStream("no-stream-stream", eventOne, {
          expectedRevision: NO_STREAM,
        });
        
        // attempt to append the same event again
        await client.appendToStream("no-stream-stream", eventTwo, {
          expectedRevision: NO_STREAM,
        });
        let data = TestEvent {
            id: "1".to_string(),
            important_data: "some value".to_string(),
        };
        
        let event = EventData::json("some-event", &data)?.id(Uuid::new_v4());
        let options = AppendToStreamOptions::default().expected_revision(ExpectedRevision::NoStream);
        
        let _ = client
            .append_to_stream("same-event-stream", &options, event)
            .await?;
        
        let data = TestEvent {
            id: "2".to_string(),
            important_data: "some other value".to_string(),
        };
        
        let event = EventData::json("some-event", &data)?.id(Uuid::new_v4());
        
        let _ = client
            .append_to_stream("same-event-stream", &options, event)
            .await?;
        // Make sure to add code blocks to your code group

        There are three available stream states:

        • Any
        • NoStream
        • StreamExists

        This check can be used to implement optimistic concurrency. When you retrieve a stream from EventStoreDB, you take note of the current version number, then when you save it back you can determine if somebody else has modified the record in the meantime.

          var clientOneRead = client.ReadStreamAsync(
          	Direction.Forwards,
          	"concurrency-stream",
          	StreamPosition.Start,
          	configureOperationOptions: options => options.ThrowOnAppendFailure = false);
          var clientOneRevision = (await clientOneRead.LastAsync()).Event.EventNumber.ToUInt64();
          
          var clientTwoRead = client.ReadStreamAsync(Direction.Forwards, "concurrency-stream", StreamPosition.Start);
          var clientTwoRevision = (await clientTwoRead.LastAsync()).Event.EventNumber.ToUInt64();
          
          var clientOneData = new EventData(
          	Uuid.NewUuid(),
          	"some-event",
          	Encoding.UTF8.GetBytes("{\"id\": \"1\" \"value\": \"clientOne\"}")
          );
          
          await client.AppendToStreamAsync(
          	"no-stream-stream",
          	clientOneRevision,
          	new List<EventData> {
          		clientOneData
          	});
          
          var clientTwoData = new EventData(
          	Uuid.NewUuid(),
          	"some-event",
          	Encoding.UTF8.GetBytes("{\"id\": \"2\" \"value\": \"clientTwo\"}")
          );
          
          await client.AppendToStreamAsync(
          	"no-stream-stream",
          	clientTwoRevision,
          	new List<EventData> {
          		clientTwoData
          	});
          
          ReadStreamOptions readStreamOptions = ReadStreamOptions.get()
                  .forwards()
                  .fromStart();
          
          ReadResult result = client.readStream("concurrency-stream", readStreamOptions)
                  .get();
          
          List<ResolvedEvent> events = result.getEvents();
          ResolvedEvent lastEvent = events.get(events.size() - 1);
          StreamRevision revision = lastEvent.getEvent().getStreamRevision();
          
          EventData clientOneData = EventData
                  .builderAsJson(
                          UUID.randomUUID(),
                          "some-event",
                          new TestEvent(
                                  "1",
                                  "clientOne"
                          ))
                  .build();
          
          EventData clientTwoData = EventData
                  .builderAsJson(
                          UUID.randomUUID(),
                          "some-event",
                          new TestEvent(
                                  "2",
                                  "clientTwo"
                          ))
                  .build();
          
          
          AppendToStreamOptions options = AppendToStreamOptions.get()
                  .expectedRevision(revision);
          
          client.appendToStream("concurrency-stream", options, clientOneData)
                  .get();
          
          client.appendToStream("concurrency-stream", options, clientTwoData)
                  .get();
          const events = await client.readStream("concurrency-stream", 10, {
            fromRevision: START,
            direction: FORWARDS,
          });
          const lastEvent = events[events.length - 1];
          const revision = lastEvent?.event?.revision;
          
          const clientOneEvent = jsonEvent({
            id: uuid(),
            type: "some-event",
            data: {
              id: "1",
              value: "some value",
            },
          });
          
          await client.appendToStream("concurrency-stream", clientOneEvent, {
            expectedRevision: revision,
          });
          
          const clientTwoEvent = jsonEvent({
            id: uuid(),
            type: "some-event",
            data: {
              id: "2",
              value: "some value",
            },
          });
          
          await client.appendToStream("concurrency-stream", clientTwoEvent, {
            expectedRevision: revision,
          });
          let options = ReadStreamOptions::default().position(StreamPosition::End);
          
          let last_event = client
              .read_stream("concurrency-stream", &options, Single)
              .await?
              .ok()
              .expect("we expect the stream to at least exist.")
              .expect("we expect the stream to have at least one event.");
          
          let data = TestEvent {
              id: "1".to_string(),
              important_data: "clientOne".to_string(),
          };
          
          let event = EventData::json("some-event", data)?.id(Uuid::new_v4());
          let options = AppendToStreamOptions::default().expected_revision(ExpectedRevision::Exact(
              last_event.get_original_event().revision,
          ));
          
          let _ = client
              .append_to_stream("concurrency-stream", &options, event)
              .await?;
          
          let data = TestEvent {
              id: "2".to_string(),
              important_data: "clientTwo".to_string(),
          };
          
          let event = EventData::json("some-event", &data)?.id(Uuid::new_v4());
          
          let _ = client
              .append_to_stream("concurrency-stream", &options, event)
              .await?;
          // Make sure to add code blocks to your code group

          # User credentials

          You can provide user credentials to be used to append the data as follows. This will override the default credentials set on the connection.

            await client.AppendToStreamAsync(
            	"some-stream",
            	StreamState.Any,
            	new[] { eventData },
            	userCredentials: new UserCredentials("admin", "changeit"),
            	cancellationToken: cancellationToken
            );
            UserCredentials credentials = new UserCredentials("admin", "changeit");
            
            AppendToStreamOptions options = AppendToStreamOptions.get()
                    .authenticated(credentials);
            
            client.appendToStream("some-stream", options, eventData)
                    .get();
            const credentials = {
              username: "admin",
              password: "changeit",
            };
            await client.appendToStream("some-stream", event, {
              credentials,
            });
            let options =
                AppendToStreamOptions::default().authenticated(Credentials::new("admin", "changeit"));
            
            let _ = client
                .append_to_stream("some-stream", &options, event)
                .await?;
            // Make sure to add code blocks to your code group
            Last Updated: 3/2/2021, 1:16:11 PM