コード例 #1
0
 public RequestResponseTypescriptContract(HttpRequestHandlerDefinition httpRequestHandlerDefinition, TypescriptContext ctx) : base(ctx)
 {
     _httpRequestHandlerDefinition = httpRequestHandlerDefinition;
     if (_httpRequestHandlerDefinition.Definition.ResponseType.GetTypeInfo().IsGenericType&&
         _httpRequestHandlerDefinition.Definition.ResponseType.GetGenericTypeDefinition() == typeof(Task <>))
     {
         _httpRequestHandlerDefinition.Definition.ResponseType = _httpRequestHandlerDefinition.Definition.ResponseType.GetGenericArguments()[0];
     }
 }
コード例 #2
0
        protected override void AdditionalGeneration(Data data, Type type, ILocalConvertContext context)
        {
            var attr = type.GetTypeInfo().GetCustomAttribute <HttpRequestAttribute>();

            if (attr == null)
            {
                throw new ArgumentNullException("attr cannot be null");
            }

            var parsed = new HttpRequestHandlerDefinition(attr, new RequestAndResponse(type));

            var queryStringParameters = ParseProperties(data, parsed, BindingType.FromQuery);
            var routeParameters       = ParseProperties(data, parsed, BindingType.FromRoute);
            var bodyParameters        = ParseProperties(data, parsed, BindingType.FromBody);

            var httpRequestType = typeof(IHttpRequest <>).MakeGenericType(parsed.Definition.ResponseType);

            var replaceRouteArgs = _.Foreach(routeParameters, prop =>
                                             $".replace('{{{prop.Original.PropertyName}}}', this.{prop.Parsed.Name} ? this.{prop.Parsed.Name}.toString() : '')");
            var hasBody = parsed.HttpMethod == HttpMethod.Patch || parsed.HttpMethod == HttpMethod.Post ||
                          parsed.HttpMethod == HttpMethod.Put;
            var body = $@"{{{
                    _.Foreach(bodyParameters, prop => $@"
        {prop.Parsed.Name}: this.{prop.Parsed.Name},").TrimEnd(',')
                }
    }}";
            var queryStringPropertyName = PropName(context, httpRequestType, nameof(IHttpRequest <object> .QueryString));
            var methodPropertyName      = PropName(context, httpRequestType, nameof(IHttpRequest <object> .Method));
            var routePropertyName       = PropName(context, httpRequestType, nameof(IHttpRequest <object> .Route));
            var bodyPropertyName        = PropName(context, httpRequestType, nameof(IHttpRequest <object> .Body));
            var code = $@"
public __name = '{context.Configuration.GetTypeName(type)}';
private __request = () => {{
    const req: {context.GetTypeScriptType(httpRequestType).ToTypeScriptType()} = {{
        {methodPropertyName}: '{parsed.HttpMethod.ToString().ToLower()}',
        {routePropertyName}: '{parsed.Route}'{replaceRouteArgs},
        {bodyPropertyName}: {(hasBody ? body : "undefined")},
        {queryStringPropertyName}: {{}}
    }};
{_getQueryStringLines(queryStringParameters.Select(x => x.Parsed), queryStringPropertyName, context)}
    return req;
}}
public execute = (dispatcher: {
                    context.GetTypeScriptType(typeof(IRequestDispatcher)).ToTypeScriptType()
                }) => dispatcher.execute(this.__request());";

            data.Body.AddRange(code.Replace("\r\n", "\n").Split('\n'));
        }
コード例 #3
0
        public OperationResult CreateCSharp(string operationName, HttpRequestHandlerDefinition builderDefinition,
                                            HashSet <string> uniqueClassNames)
        {
            var requestBodyProperties = builderDefinition.Parameters.Where(x => x.BindingType == BindingType.FromBody || x.BindingType == BindingType.FromForm).ToArray();
            var requestClass          = builderDefinition.Definition.RequestType.Name;
            var original = requestClass;
            var tryCount = 1;

            while (uniqueClassNames.Contains(requestClass))
            {
                requestClass = $"{original}_{++tryCount}";
            }

            var methodArgs = string.Join(",  ", builderDefinition.Parameters.GroupBy(x => x.PropertyName).Select(x => new
            {
                Name   = x.Key,
                Type   = x.First().BindingType == BindingType.FromBody || x.First().BindingType == BindingType.FromForm ? requestClass : GetCorrectFormat(x.First().PropertyInfo.PropertyType),
                Binder = x.First().BindingType
            }).Select(x => $"[Microsoft.AspNetCore.Mvc.{x.Binder}Attribute] {x.Type} {x.Name}"));
            var isAsync = builderDefinition.Definition.ResponseType.IsConstructedGenericType &&
                          builderDefinition.Definition.ResponseType.GetGenericTypeDefinition() == typeof(Task <>);
            var responseType = isAsync
                ? builderDefinition.Definition.ResponseType.GetGenericArguments()[0]
                : builderDefinition.Definition.ResponseType;
            var requestVariable = "request_" + Guid.NewGuid().ToString().Replace("-", "");
            var operationResult = new OperationResult();

            operationResult.OperationName = operationName;
            operationResult.RequestClass  = $@"public class {requestClass}
{{{CodeStr.Foreach(requestBodyProperties, source => $@"
    public {GetCorrectFormat(source.PropertyInfo.PropertyType)} {source.PropertyInfo.Name} {{ get; set; }}")}
}}";
            operationResult.Operation     = $@"{GetAttributes(builderDefinition.Definition)}[Microsoft.AspNetCore.Mvc.Http{builderDefinition.HttpMethod}Attribute(""{builderDefinition.Route}""), {GetCorrectFormat(typeof(ProducesAttribute))}(typeof({GetCorrectFormat(responseType)}))]
public  {(isAsync ? "async " : string.Empty)}{GetCorrectFormat(isAsync ? typeof(Task<IActionResult>) : typeof(IActionResult))} {operationName}({methodArgs})
{{
    var {requestVariable} = new {GetCorrectFormat(builderDefinition.Definition.RequestType)}
    {{{CodeStr.Foreach(builderDefinition.Parameters, assignment => $@"
        {assignment.PropertyInfo.Name} = {assignment.PropertyName}{(assignment.BindingType == BindingType.FromBody || assignment.BindingType == BindingType.FromForm ? $".{assignment.PropertyInfo.Name}" : "")},").Trim(',')}
    }};

    var response = {(isAsync ? "await " : string.Empty)}_requestProcessor.Process{(isAsync ? "Async" : string.Empty)}<{GetCorrectFormat(builderDefinition.Definition.RequestType)},{GetCorrectFormat(responseType)}>({requestVariable}, this);
    return response;
}}";
            return(operationResult);
        }
コード例 #4
0
        public OperationResult CreateCSharp(string operationName, HttpRequestHandlerDefinition builderDefinition)
        {
            var requestBodyProperties = builderDefinition.Parameters.Where(x => x.BindingType == BindingType.FromBody || x.BindingType == BindingType.FromForm).ToArray();
            var requestClass          = builderDefinition.Definition.RequestType.Name + "_" + Guid.NewGuid().ToString().Replace("-", "");


            var methodArgs = string.Join(",  ", builderDefinition.Parameters.GroupBy(x => x.PropertyName).Select(x => new
            {
                Name        = x.Key,
                Type        = x.First().BindingType == BindingType.FromBody || x.First().BindingType == BindingType.FromForm ? requestClass : GetCorrectFormat(x.First().PropertyInfo.PropertyType),
                Binder      = x.First().BindingType == BindingType.FromBody ? "FromBody" : "FromUri",
                BindingType = x.First().BindingType
            }).Select(x => $"[System.Web.Http.{x.Binder}Attribute] {x.Type} {x.Name}{CodeStr.If(x.BindingType == BindingType.FromQuery, $" = default({x.Type})")}"));
            var isAsync = builderDefinition.Definition.ResponseType.IsConstructedGenericType &&
                          builderDefinition.Definition.ResponseType.GetGenericTypeDefinition() == typeof(Task <>);
            var responseType = isAsync
                ? builderDefinition.Definition.ResponseType.GetGenericArguments()[0]
                : builderDefinition.Definition.ResponseType;
            var requestVariable = "request_" + Guid.NewGuid().ToString().Replace("-", "");

            var operationResult = new OperationResult();

            operationResult.OperationName = operationName;
            operationResult.RequestClass  = $@"public class {requestClass}
{{{CodeStr.Foreach(requestBodyProperties, source => $@"
    public {GetCorrectFormat(source.PropertyInfo.PropertyType)} {source.PropertyInfo.Name} {{ get; set; }}")}
}}";
            operationResult.Operation     = $@"[System.Web.Http.Http{builderDefinition.HttpMethod}Attribute, {GetCorrectFormat(typeof(RouteAttribute))}(""{ builderDefinition.Route}""), {GetCorrectFormat(typeof(ResponseTypeAttribute))}(typeof({GetCorrectFormat(responseType)}))]
public  {(isAsync ? "async " : string.Empty)}{GetCorrectFormat(isAsync ? typeof(Task<IHttpActionResult>) : typeof(IHttpActionResult))} {operationName}({methodArgs})
{{
    var {requestVariable} = new {GetCorrectFormat(builderDefinition.Definition.RequestType)}();{CodeStr.Foreach(builderDefinition.Parameters, assignment => $@"
    {requestVariable}.{assignment.PropertyInfo.Name} = {assignment.PropertyName}{(assignment.BindingType == BindingType.FromBody || assignment.BindingType == BindingType.FromForm ? $".{assignment.PropertyInfo.Name}" : "")};")}

    var response = {(isAsync ? "await " : string.Empty)}_requestProcessor.Process{(isAsync ? "Async" : string.Empty)}<{GetCorrectFormat(builderDefinition.Definition.RequestType)},{GetCorrectFormat(responseType)}>({requestVariable}, this);
    return response;
}}";
            return(operationResult);
        }
コード例 #5
0
        private static IEnumerable <ParsedProperty> ParseProperties(Data data, HttpRequestHandlerDefinition requestHandlerDefinition, BindingType bindingType)
        {
            var propertyBindings = requestHandlerDefinition.Parameters.Where(x => x.BindingType == bindingType);

            return(propertyBindings.Select(x => new ParsedProperty(x, data.Properties.Single(p => p.PropertyInfo == x.PropertyInfo))));
        }