using SpacetimeDB; public static partial class Module { [Reducer(ReducerKind.ClientConnected)] public static void ClientConnected(ReducerContext ctx) { Log.Info($"Connect {ctx.Sender}"); var user = ctx.Db.User.Identity.Find(ctx.Sender); if (user is not null) { // If this is a returning user, i.e., we already have a `User` with this `Identity`, // set `Online: true`, but leave `Name` and `Identity` unchanged. user.Online = true; ctx.Db.User.Identity.Update(user); } else { // If this is a new user, create a `User` object for the `Identity`, // which is online, but hasn't set a name. ctx.Db.User.Insert( new User { Name = null, Identity = ctx.Sender, Online = true, } ); } } [Reducer(ReducerKind.ClientDisconnected)] public static void ClientDisconnected(ReducerContext ctx) { var user = ctx.Db.User.Identity.Find(ctx.Sender); if (user is not null) { // This user should exist, so set `Online: false`. user.Online = false; ctx.Db.User.Identity.Update(user); } else { // User does not exist, log warning Log.Warn("Warning: No user found for disconnected client."); } } }