Skip to content

Instantly share code, notes, and snippets.

@benfoster
Last active February 1, 2019 06:36
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benfoster/48b2f9dfafb0dd2a342e0f83ca8cc1c9 to your computer and use it in GitHub Desktop.
Save benfoster/48b2f9dfafb0dd2a342e0f83ca8cc1c9 to your computer and use it in GitHub Desktop.
public static void Execute(ChargeCommand command)
{
var pipeline = new PipelineBuilder<ChargeContext>()
.Register(new TimingHandler())
.Register(new LoggingHandler())
.Register(new ValidationHandler(
validationPipeline =>
{
validationPipeline.Register(new AmountValidator(maxAmount: 500));
}
))
.Register(new RiskHandler(
riskPipeline =>
{
riskPipeline.Register(new CardholderRiskCheck());
riskPipeline.Register(new CountryRiskCheck());
}
))
.Register(() => new AuthorizeChargeHandler()) // Lazily constructed
.Build();
var context = new ChargeContext
{
Request = new ChargeRequest
{
Cardholder = command.Cardholder,
Country = command.Country,
CardNumber = command.CardNumber,
Amount = command.Amount.Value
}
};
pipeline.Invoke(context).Wait();
}
using System;
using System.Threading.Tasks;
using Checkout.Pipelines.Charges;
namespace Checkout.Pipelines.Risk
{
public class RiskHandler : PipelineHandler<ChargeContext>
{
Action<PipelineBuilder<RiskContext>> configure;
public RiskHandler(Action<PipelineBuilder<RiskContext>> configure)
{
this.configure = configure;
}
public override async Task HandleAsync(ChargeContext context, Func<ChargeContext, Task> next)
{
Console.WriteLine("Checking Risk");
var riskContext = new RiskContext
{
ChargeRequest = context.Request
};
var pipelineBuilder = new PipelineBuilder<RiskContext>();
configure(pipelineBuilder);
var riskPipeline = pipelineBuilder.Build();
// Invoke the validation pipeline
await riskPipeline.Invoke(riskContext);
if (riskContext.Risk >= 100)
{
context.Response = new ChargeResponse
{
Message = $"Risk check failed. Risk value: {riskContext.Risk}"
};
}
else
{
await next(context);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment