How can I get the last event from an Event Store stream with only one HTTP request?
Asked Answered
B

3

5

All the docs I can find seem to suggest I need two http requests to do this: one to the stream, giving me a link to the last event, and then one to follow that link.

That seems bizarre, isn't there a way to do this with just one request?

Bargello answered 13/11, 2017 at 22:10 Comment(2)
it is a question that i am researching to, you can use "SubscribeToStreamFrom" from the client api but then you still need to get the last event from the stream.Lunation
@HomeForce i got it just after I posted this and forgot to update, sorry! Have posted the answer now.Bargello
B
4

The keyword is 'head', like git. So the last event is at [url of the stream]/head.

Bargello answered 15/11, 2017 at 0:20 Comment(0)
T
4

If using the .NET Client you can also use the read backwards API

Task<StreamEventsSlice> ReadStreamEventsBackwardAsync(string stream, int start, int count, bool resolveLinkTos)

Where

  • Start - Generally if you know which event number to start from but in this case we do not know so we can StreamPosition.End (-1) to start from the end.
  • Count - How many events to get going backwards

So this code will get you the last event on the stream (with linkTos enabled if its a projection)

 StreamEventsSlice slice = await Connection.ReadStreamEventsBackwardAsync("StreamName", StreamPosition.End, 1, true, creds);
Tesler answered 11/7, 2018 at 14:27 Comment(0)
C
0

An alternative if you are using the EventStore gRPC client.

_client.ReadStreamAsync(Direction.Backwards, _streamName, StreamPosition.End, 1)

Very similar to the .NET version. You're requesting the stream to be read backwards starting at the end of the stream, and to return only one event.

Your result is then an iterable that will contain only one item - the latest event

Reading from a stream - reading backwards

Chape answered 12/8, 2021 at 9:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.