Skip to content

Provide Overload for Keys of Type Guid #26

@endeffects

Description

@endeffects

It would be nice if you can add the following extension methods to improve the usage.

Usage

await sessionStorage.CreateOrUpdate<SomeStateObject>(notification.Id, state => state.OnNotification(notification));

Instead of

var state = await sessionStorage.GetItem<SomeStateObject>(notification.Id) ?? new new SomeStateObject();
state.OnNotification(notification);
await sessionStorage.SetItem<SomeStateObject>(notification.Id, state);

Extensions

    public static class StorageExtensions
    {
        public static async Task<TState> CreateOrUpdate<TState>(this IStorage storage, Guid id, Action<TState> handler) where TState : class, IState
        {
            var state = await storage.GetItem<TState>($"{id}") ?? Activator.CreateInstance<TState>();

            handler(state);

            await storage.SetItem($"{id}", state);

            return state;
        }

        public static async Task<TState> Update<TState>(this IStorage storage, Guid id, Action<TState> handler) where TState : class, IState
        {
            var state = await storage.GetItem<TState>($"{id}");

            if (state == null)
            {
                throw new InvalidOperationException("State not found!");
            }

            handler(state);

            await storage.SetItem($"{id}", state);

            return state;
        }
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions