private async Task HandleCommand(HttpContext context, ICqrsOptions options) { var path = options.GetCommandPath(context.Request.Path.Value); if (!_commandTypes.Value.ContainsKey(path)) { throw new CommandNotFoundException($"Command '{path}' not found"); } dynamic result = null; var info = _commandTypes.Value[path]; var exposeAttribute = info.CommandType.GetCustomAttribute <ExposeAttribute>(); var formatter = _registry.GetFormatter(exposeAttribute.Formatter); var deserializeMethod = _deserializeMethods.GetOrAdd(info.CommandType, (t) => { var mi = CreateDeserializeLambdaMethodInfo.MakeGenericMethod(t); return(mi.Invoke(null, null)); }); dynamic command = await deserializeMethod(formatter, context.Request); dynamic handler = _container.GetInstance(info.CommandHandlerType); context.Items[ContextKey] = new CqrsContext(context.Request.Path.Value, path, CqrsType.Command, info.CommandHandlerType); if (info.IsGeneric) { if (info.IsAsync) { result = await handler.HandleAsync(command, context.RequestAborted); } else { result = handler.Handle(command); } } else { if (info.IsAsync) { await handler.HandleAsync(command, context.RequestAborted); } else { handler.Handle(command); } } CloseSession(); var json = result is string?result : await formatter.SerializeAsync(result, context.Request); context.Response.ContentType = formatter.ContentType; context.Response.StatusCode = (int)HttpStatusCode.OK; await HttpResponseWritingExtensions.WriteAsync(context.Response, json, context.RequestAborted); }
private async Task HandleQuery(HttpContext context, ICqrsOptions options) { var path = context.Request.Path.Value; var method = context.Request.Method; if (!_queryTypes.Value.ContainsKey($"{method} {path}")) { throw new QueryNotFoundException($"Query '{method} {path}' not found"); } var info = _queryTypes.Value[$"{method} {path}"]; var exposeAttribute = info.QueryType.GetCustomAttribute <ExposeAttribute>(); var formatter = _registry.GetFormatter(exposeAttribute.Formatter); var deserializeMethod = _deserializeMethods.GetOrAdd(info.QueryType, (t) => { var mi = CreateDeserializeLambdaMethodInfo.MakeGenericMethod(t); return(mi.Invoke(null, null)); }); var query = await deserializeMethod(formatter, context.Request); dynamic handler = options.GetInstance(info.QueryHandlerType); context.Items[IOwinContextExtensions.ContextKey] = new CqrsContext(context.Request.Path.Value, path, CqrsType.Command, info.QueryHandlerType); dynamic result; if (info.IsAsync) { result = await handler.HandleAsync(query, context.RequestAborted); } else { result = handler.Handle(query); } string json = null; if (result != null) { json = result is string?result : await formatter.SerializeAsync(result, context.Request); } context.Response.ContentType = formatter.ContentType; if (json != null) { context.Response.StatusCode = (int)HttpStatusCode.OK; await context.Response.WriteAsync(json, context.RequestAborted); } else { context.Response.StatusCode = (int)HttpStatusCode.NoContent; } }