Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide Overload for Keys of Type Guid #26

Open
endeffects opened this issue May 4, 2019 · 0 comments
Open

Provide Overload for Keys of Type Guid #26

endeffects opened this issue May 4, 2019 · 0 comments

Comments

@endeffects
Copy link

endeffects commented May 4, 2019

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;
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant