Skip to content

Instantly share code, notes, and snippets.

@dgg
Last active November 26, 2017 13:13
Show Gist options
  • Save dgg/163fbf97c020539857d0521f0711d6be to your computer and use it in GitHub Desktop.
Save dgg/163fbf97c020539857d0521f0711d6be to your computer and use it in GitHub Desktop.
samplify-swagger
services.AddSwaggerGen(o =>
{
o.SchemaFilter<SampleFilter>();
// ...
})
[HasCustomSample]
public class OneRequest
{
public int I { get; set; }
public string S { get; set; }
public bool B { get; set; }
public decimal N { get; set; }
public InputDto D { get; set; }
}
public class InputDto
{
[SampleValue(42)]
public int I { get; set; }
[SampleValue("meaningful")]
public string S { get; set; }
[SampleValues("a", "b")]
public string[] A { get; set; }
}
internal class SampleFilter : ISchemaFilter
{
public void Apply(Schema model, SchemaFilterContext context)
{
var attribute = context.SystemType.GetCustomAttribute<HasCustomSampleAttribute>();
if (attribute != null)
{
model.Example = attribute.BuildExample(context.SystemType);
}
}
}
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public sealed class SampleValueAttribute : Attribute
{
public SampleValueAttribute(object value)
{
Value = value;
}
public object Value { get; }
private object AssignableValue(PropertyInfo property)
{
object assignableValue = Value;
if (Value != null && !property.PropertyType.IsAssignableFrom(Value.GetType()))
{
assignableValue = Convert.ChangeType(Value, property.PropertyType);
}
return assignableValue;
}
public class SpecimenBuilder : ISpecimenBuilder
{
public object Create(object request, ISpecimenContext context)
{
object result = new NoSpecimen();
PropertyInfo property = request as PropertyInfo;
if (property != null)
{
var attribute = property.GetCustomAttribute<SampleValueAttribute>();
if (attribute != null)
{
result = attribute.AssignableValue(property);
}
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment