Ejemplo n.º 1
0
        public async Task <ExecutionData> ProcessAsync(RouteConfig routeConfig,
                                                       HttpRequest request, HttpResponse response, RouteData data)
        {
            request.Headers.TryGetValue("content-type", out var contentType);
            var requestId     = Guid.NewGuid().ToString();
            var resourceId    = Guid.NewGuid().ToString();
            var executionData = new ExecutionData
            {
                RequestId   = requestId,
                ResourceId  = resourceId,
                Route       = routeConfig.Route,
                Request     = request,
                Response    = response,
                Data        = data,
                Downstream  = GetDownstream(routeConfig, request, data),
                Payload     = await GetPayloadAsync(resourceId, routeConfig.Route, request, data),
                UserId      = _valueProvider.Get("@user_id", request, data),
                ContentType = contentType,
            };

            if (_messages.TryGetValue(GetMessagesKey(routeConfig.Route), out var dataAndSchema))
            {
                executionData.ValidationErrors = await GetValidationErrorsAsync(routeConfig.Route,
                                                                                executionData.Payload, dataAndSchema.Value);
            }

            return(executionData);
        }
 public IEnumerable <string> Get()
 {
     return(new [] {
         _valueProvider.Get(),
         _valueProvider.Get()
     });
 }
Ejemplo n.º 3
0
        public IEnumerable <string> Get()
        {
            var builder1 = _builderFactory(1);
            var builder2 = _builderFactory(2);

            return(new[] {
                _valueProvider.Get(),
                _valueProvider.Get(),
                builder1.Build(),
                builder2.Build(),
            });
        }
Ejemplo n.º 4
0
        /// <summary>
        ///		Create a copy of the request that adds a header to each request.
        /// </summary>
        /// <typeparam name="TContext">
        ///		The type of object used as a context for resolving deferred parameters.
        /// </typeparam>
        /// <param name="request">
        ///		The HTTP request.
        /// </param>
        /// <param name="headerName">
        ///		The header name.
        /// </param>
        /// <param name="valueProvider">
        ///		The header value provider.
        /// </param>
        /// <param name="ensureQuoted">
        ///		Ensure that the header value is quoted?
        /// </param>
        /// <returns>
        ///		The new <see cref="HttpRequest{TContext}"/>.
        /// </returns>
        public static HttpRequest <TContext> WithHeaderFromProvider <TContext>(this HttpRequest <TContext> request, string headerName, IValueProvider <TContext, string> valueProvider, bool ensureQuoted = false)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (String.IsNullOrWhiteSpace(headerName))
            {
                throw new ArgumentException("Argument cannot be null, empty, or composed entirely of whitespace: 'name'.", nameof(headerName));
            }

            if (valueProvider == null)
            {
                throw new ArgumentNullException(nameof(valueProvider));
            }

            return(request.WithRequestAction((requestMessage, context) =>
            {
                requestMessage.Headers.Remove(headerName);

                string headerValue = valueProvider.Get(context);
                if (headerValue == null)
                {
                    return;
                }

                if (ensureQuoted)
                {
                    headerValue = EnsureQuoted(headerValue);
                }

                requestMessage.Headers.Add(headerName, headerValue);
            }));
        }
        /// <summary>
        ///		Wrap the specified value provider in a value provider that utilises a more-derived context type.
        /// </summary>
        /// <typeparam name="TDerivedContext">
        ///		The more-derived type used by the new provider as a context for each request.
        /// </typeparam>
        /// <returns>
        ///		The outer (converting) value provider.
        /// </returns>
        public IValueProvider <TDerivedContext, TValue> ContextTo <TDerivedContext>()
            where TDerivedContext : TContext
        {
            // Can't close over members of structs.
            IValueProvider <TContext, TValue> valueProvider = ValueProvider;

            return(ValueProvider <TDerivedContext> .FromSelector(
                       context => valueProvider.Get(context)
                       ));
        }
Ejemplo n.º 6
0
        public PayloadSchema Transform(string payload, string resourceId, Route route, HttpRequest request, RouteData data)
        {
            var payloadKey = GetPayloadKey(route);
            var command    = _payloads.ContainsKey(payloadKey)
                ? GetObjectFromPayload(route, payload)
                : GetObject(payload);

            var commandValues = (IDictionary <string, object>)command;

            if (!string.IsNullOrWhiteSpace(resourceId))
            {
                var resourceIdProperty = string.IsNullOrWhiteSpace(route.ResourceId?.Property)
                    ? _options.ResourceId.Property
                    : route.ResourceId?.Property;
                if (string.IsNullOrWhiteSpace(resourceIdProperty))
                {
                    resourceIdProperty = ResourceIdProperty;
                }

                commandValues[resourceIdProperty] = resourceId;
            }

            foreach (var setter in route.Bind ?? Enumerable.Empty <string>())
            {
                var keyAndValue = setter.Split(':');
                var key         = keyAndValue[0];
                var value       = keyAndValue[1];
                commandValues[key] = _valueProvider.Get(value, request, data);
                var routeValue = value.Length > 2 ? value.Substring(1, value.Length - 2) : string.Empty;
                if (data.Values.TryGetValue(routeValue, out var dataValue))
                {
                    commandValues[key] = dataValue;
                }
            }

            foreach (var transformation in route.Transform ?? Enumerable.Empty <string>())
            {
                var beforeAndAfter = transformation.Split(':');
                var before         = beforeAndAfter[0];
                var after          = beforeAndAfter[1];
                if (!commandValues.TryGetValue(before, out var value))
                {
                    continue;
                }

                commandValues.Remove(before);
                commandValues.Add(after, value);
            }

            _payloads.TryGetValue(payloadKey, out var payloadSchema);

            return(new PayloadSchema(command as ExpandoObject, payloadSchema?.Schema));
        }
Ejemplo n.º 7
0
        public string GetDownstream(RouteConfig routeConfig, HttpRequest request, RouteData data)
        {
            if (string.IsNullOrWhiteSpace(routeConfig.Downstream))
            {
                return(null);
            }

            var stringBuilder = new StringBuilder();
            var downstream    = routeConfig.Downstream;

            stringBuilder.Append(downstream);
            if (downstream.Contains("@"))
            {
                foreach (var token in _valueProvider.Tokens)
                {
                    var tokenName = $"@{token}";
                    stringBuilder.Replace(tokenName, _valueProvider.Get(tokenName, request, data));
                }
            }

            foreach (var(key, value) in data.Values)
            {
                if (value is null)
                {
                    continue;
                }

                if (key is "url")
                {
                    stringBuilder.Append($"/{value}");
                    continue;
                }

                stringBuilder.Replace($"{{{key}}}", value.ToString());
            }

            if (_options.PassQueryString == false || routeConfig.Route.PassQueryString == false)
            {
                return(stringBuilder.ToString());
            }

            var queryString = request.QueryString.ToString();

            if (downstream.Contains("?") && !string.IsNullOrWhiteSpace(queryString))
            {
                queryString = $"&{queryString.Substring(1, queryString.Length - 1)}";
            }

            stringBuilder.Append(queryString);

            return(stringBuilder.ToString());
        }
        public string RequestValueAndSaving(string name, IValueValidator validator, IValueProvider valueProvider)
        {
            var result = validator.Validate(valueProvider?.Get(name));

            while (!result.IsValid)
            {
                Console.WriteLine(Resources.PleaseEnterValue, name);
                result = validator.Validate(Console.ReadLine());
                if (!result.IsValid)
                {
                    Console.WriteLine(result.Value);
                    continue;
                }

                RequestValueSaving(name, result.Value, valueProvider);
            }

            return(result.Value);
        }
        /// <summary>
        ///		Wrap the value provider in a value provider that converts its value to a string.
        /// </summary>
        /// <returns>
        ///		The outer (converting) value provider.
        /// </returns>
        /// <remarks>
        ///		If the underlying value is <c>null</c> then the converted string value will be <c>null</c>, too.
        /// </remarks>
        public IValueProvider <TContext, string> ValueToString()
        {
            // Special-case conversion to save on allocations.
            if (typeof(TValue) == typeof(string))
            {
                return((IValueProvider <TContext, string>)ValueProvider);
            }

            // Can't close over members of structs.
            IValueProvider <TContext, TValue> valueProvider = ValueProvider;

            return(ValueProvider <TContext> .FromSelector(
                       context =>
            {
                TValue value = valueProvider.Get(context);

                return value != null ? value.ToString() : null;
            }
                       ));
        }
Ejemplo n.º 10
0
        private async Task <Result <string, string> > TryResolveAsync(
            string input,
            ValueAddress address
            )
        {
            try
            {
                var entity = await provider
                             .Get(address.EntityAddress);

                if (entity == null)
                {
                    return(new Result(error: $"Entity not found: {address.EntityAddress}"));
                }

                string GetEntityPropertyValue(IEnumerable <string> path)
                {
                    var _path = string.Join(".", path);
                    var value = entity.SelectToken(_path);

                    if (value == null)
                    {
                        throw new Exception($"No value at path: {_path}");
                    }
                    return(value.ToString());
                }

                var output = input.Replace(
                    oldValue: address.ToInterpolationString(),
                    newValue: GetEntityPropertyValue(address.PropertyPath),
                    comparisonType: StringComparison.OrdinalIgnoreCase
                    );

                return(new Result(ok: output));
            }
            catch (Exception ex)
            {
                return(new Result(error: ex.Message));
            }
        }