-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathProgram.cs
60 lines (47 loc) · 1.93 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System.Text.Json;
using EventStore.Client;
using System.ComponentModel;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Register the EventStoreClient as a Singleton
builder.Services.AddSingleton(
new EventStoreClient(EventStoreClientSettings.Create(
"esdb://admin:changeit@esdb-local:2113?tls=false&tlsVerifyCert=false")));
var app = builder.Build();
app.UseHttpsRedirection();
app.UseSwagger();
app.UseSwaggerUI();
const string visitorsStream = "visitors-stream";
app.MapGet("/hello-world", async (
[FromQuery] [DefaultValue("Visitor")] string visitor,
[FromServices] EventStoreClient eventStore,
CancellationToken cancellationToken) =>
{
var visitorGreeted = new VisitorGreeted(visitor);
var eventData = new EventData(
Uuid.NewUuid(),
nameof(VisitorGreeted),
JsonSerializer.SerializeToUtf8Bytes(visitorGreeted));
await eventStore.AppendToStreamAsync(
visitorsStream,
StreamState.Any,
new[] { eventData },
cancellationToken: cancellationToken);
var readStreamResult = eventStore.ReadStreamAsync(
Direction.Forwards,
visitorsStream,
StreamPosition.Start,
cancellationToken: cancellationToken);
var eventStream = await readStreamResult.ToListAsync(cancellationToken);
var visitorsGreeted = eventStream
.Select(re => JsonSerializer.Deserialize<VisitorGreeted>(re.Event.Data.ToArray()))
.Select(vg => vg!.Visitor)
.ToArray();
return Results.Ok($"{visitorsGreeted.Length} visitors have been greeted, they are: [{string.Join(',', visitorsGreeted)}]");
})
.WithName("HelloWorld")
.WithOpenApi();
app.Run();
internal record VisitorGreeted(string Visitor);