private IEnumerable <object> GetArguments(IResolveFieldContext context) { foreach (var parameter in this._Method.Parameters) { var graphAttribute = parameter.Attributes.GraphName() ?? parameter.Name; if (parameter.Attributes.GraphIgnore()) { continue; } if (parameter.Type.Is <IResolveFieldContext>() || parameter.Type.Is(typeof(IResolveFieldContext <>))) { yield return(context); } else if (parameter.Type.SystemType == SystemType.Unknown) { var argument = context.GetArgument <IDictionary <string, object?> >(parameter.Name); var model = parameter.Type.Create(); if (argument is not null) { model.ReadProperties(argument); } yield return(model); } else { yield return(context.GetArgument(parameter.Type, parameter.Name)); // TODO: Support a default value? } } }
private async Task <IEnumerable <Log> > GetLogFunc(IResolveFieldContext <object> context) { var logId = context.GetArgument <string>("logId"); if (logId != null) { var log = await _logEngine.GetLog(logId); return(new List <Log> { log }); } var missionId = context.GetArgument <string>("missionId"); if (missionId != null) { return(await _logEngine.GetLogsByMissionId(missionId)); } var seriesId = context.GetArgument <string>("seriesId"); if (seriesId != null) { return(await _logEngine.GetLogsBySeriesId(seriesId)); } return(await _logEngine.GetAll()); }
private async Task <object> ResolvePatchFlight(IResolveFieldContext <object> context) { var id = context.GetArgument <string>("id"); var flightInput = context.GetArgument <FlightData>("flight"); return(await flightStorage.PatchAsync(id, flightInput)); }
internal override async Task <ExpenseModel> ResolveAsync(IResolveFieldContext <object> context) { var id = context.GetArgument <int>(_IdArgumentName); var model = context.GetArgument <UpdateExpenseModel>(_UpdateArgumentName); using var scope = new Scope(context.RequestServices); return(await scope.Sender.Send(new UpdateExpenseRequest(id, model), context.CancellationToken)); }
internal override async Task <ProjectPermissionModel> ResolveAsync(IResolveFieldContext <object> context) { var projectId = context.GetArgument <int>(_ProjectIdArgumentName); var userId = context.GetArgument <int>(_UserIdArgumentName); using var scope = new Scope(context.RequestServices); return(await scope.Sender.Send(new DeleteProjectPermissionRequest(projectId : projectId, userId : userId), context.CancellationToken)); }
private static async Task <List <User> > FetchUsers(IQueryable <User> query, IResolveFieldContext context) { return(await query .OrderBy(context.GetArgument(Args.Sorting, "Name,Surname")) .PageBy(context.GetArgument <int>(Args.SkipCount), context.GetArgument(Args.MaxResultCount, AppConsts.DefaultPageSize)) .ToListAsync()); }
private IProduct ResolveProduct(IResolveFieldContext <Object> context) { var id = context.GetArgument <String>(idArg); var type = context.GetArgument <String>(typeArg); var products = _repo.Where(product => product.Id == id); if (!String.IsNullOrEmpty(type)) { products = products.Where(product => product.Type == type); } return(products.FirstOrDefault()); }
private static Connection <T> GetConnection <T>( IResolveFieldContext context, IQueryable <T> dbSet, Func <string, Expression <Func <T, bool> > > filterExpression, Expression <Func <T, object> > orderByName, Expression <Func <T, object> > orderByTimeAdded, Expression <Func <T, object?> > orderByLastPlayed ) where T : class { var first = context.GetArgument("first", 25); var after = context.GetArgument <string?>("after"); var offset = after == null ? 0 : int.Parse(after); var sort = context.GetArgument("sort", new SortParams { SortBy = SortBy.Lexicographically }); var baseQuery = sort.Filter != null?dbSet.Where(filterExpression(sort.Filter)) : dbSet; var query = sort.SortBy switch { SortBy.RecentlyAdded => sort.Reverse ? baseQuery.OrderByDescending(orderByTimeAdded) : baseQuery.OrderBy(orderByTimeAdded), SortBy.Lexicographically => sort.Reverse ? baseQuery.OrderByDescending(orderByName) : baseQuery.OrderBy(orderByName), SortBy.RecentlyPlayed => sort.Reverse ? baseQuery.OrderByDescending(orderByLastPlayed) : baseQuery.OrderBy(orderByLastPlayed), _ => throw new ArgumentOutOfRangeException( nameof(sort.SortBy), "Missing a SortBy case in GetConnection" ) }; var results = query.Skip(offset).Take(first).ToList(); var edges = results .Zip(Enumerable.Range(1, Int32.MaxValue)) .Select((item) => new Edge <T> { Cursor = (offset + item.Second).ToString(), Node = item.First }) .ToList(); var totalCount = baseQuery.Count(); var hasNextPage = offset + first < totalCount; return(new Connection <T> { Edges = edges, PageInfo = new PageInfo { HasNextPage = hasNextPage }, TotalCount = totalCount }); }
internal override async Task <ProjectInviteModel> ResolveAsync(IResolveFieldContext <object> context) { var id = context.GetArgument <int>(_IdArgumentName); using var scope = new Scope(context.RequestServices); return(await scope.Sender.Send(new DeleteProjectInviteRequest(id), context.CancellationToken)); }
public async Task <SqlResponse <T> > DeleteBatch([NotNull] T[] batch, IResolveFieldContext context) { var selections = context.GetQuerySelections().ToArray(); var columns = context.GetArgument <IDictionary <string, object> >(nameof(batch)).Keys.ToArray(); var request = new BatchRequest { Delete = true, Table = this.Table, Input = batch.MapRowSet(columns) }; selections .If(selection => selection.Left(nameof(SqlResponse <T> .Data))) .To(selection => selection.TrimStart($"{nameof(SqlResponse<T>.Data)}.") !) .Do(selection => request.Output[selection] = "DELETED"); var sqlResponse = new SqlResponse <T>(); if (selections.Has(nameof(SqlResponse <T> .Table))) { sqlResponse.Table = this.Table; } if (selections.Any(selection => selection.Left(nameof(SqlResponse <T> .SQL)))) { sqlResponse.SQL = await this._Mediator.ApplyRulesAsync <BatchRequest, string>(request); } if (request.Output.Any()) { var data = await this._Mediator.ApplyRulesAsync <(ISqlApi, BatchRequest), RowSet>((this._SqlApi, request)); sqlResponse.Data = data?.Rows is not null?data.MapModels <T>() : Array <T> .Empty; } return(sqlResponse); }
public static IQueryable <TItem> ApplyGraphQlArguments <TItem>(this IQueryable <TItem> queryable, IResolveFieldContext context, List <string>?keyNames = null) where TItem : class { Guard.AgainstNull(nameof(queryable), queryable); Guard.AgainstNull(nameof(context), context); return(ApplyToAll(queryable, (type, x) => context.GetArgument(type, x), keyNames)); }
internal override async Task <SummaryModel> ResolveAsync(IResolveFieldContext <object> context) { var filter = context.GetArgument <SummaryFilterModel>(_FilterArgumentName); using var scope = new Scope(context.RequestServices); return(await scope.Sender.Send(new SummaryRequest(filter), context.CancellationToken)); }
private async Task <IEnumerable <Event> > GetEventFunc(IResolveFieldContext <object> context) { var eventId = context.GetArgument <string>("eventId"); if (eventId != null) { var @event = await _eventEngine.GetEvent(eventId); return(new List <Event> { @event }); } var missionId = context.GetArgument <string>("missionId"); return(await _eventEngine.GetEventsByMissionId(missionId)); }
public async Task <TSource> UpdateAsync <TSource>(IResolveFieldContext <object> context, string sourceName, Func <ClaimsPrincipal, AssertAction, bool> claimsPrincipalAssertion) where TSource : class { AssertWithClaimsPrincipal(AssertAction.Update, context, claimsPrincipalAssertion); var item = context.GetArgument <TSource>(sourceName); var ctx = context.GetGraphRequestContext(); await TransformObject(item, ctx, MutationActions.Update); var cloned = item.Clone(); try { var mutationActionItem = new MutationActionItem <TSource> { Action = MutationActions.Update, RequestContext = ctx, Item = item, RepositoryProvider = _graphQlRepositoryProvider }; await _mutationActionsProvider.HandlePreActions(mutationActionItem); await _graphQlRepositoryProvider.GetRepository <TSource>().UpdateAsync(item, context.GetGraphRequestContext()); await _mutationActionsProvider.HandlePostActions(mutationActionItem); } catch (Exception e) { _logger.LogError(e, "An error has occured while performing an update operation."); throw; } return(cloned); }
internal override async Task <ProjectModel> ResolveAsync(IResolveFieldContext <object> context) { var model = context.GetArgument <CreateProjectModel>(_ProjectArgumentName); using var scope = new Scope(context.RequestServices); return(await scope.Sender.Send(new CreateProjectRequest(model), context.CancellationToken)); }
private object ResolveObjectFromGlobalId(IResolveFieldContext <object> context) { var globalId = context.GetArgument <string>("id"); var parts = Node.FromGlobalId(globalId); var node = context.Schema.AllTypes[parts.Type] as IRelayNode <object>; return(node.GetById(context, parts.Id)); }
public async Task <TSource> DeleteAsync <TSource>(IResolveFieldContext <object> context, string sourceName, Func <ClaimsPrincipal, AssertAction, bool> claimsPrincipalAssertion) where TSource : class { AssertWithClaimsPrincipal(AssertAction.Delete, context, claimsPrincipalAssertion); var item = context.GetArgument <TSource>(sourceName); return(await InternalDeleteAsync(context, item)); }
private Func <Game, bool> GetGamesFilter(IResolveFieldContext <object> context) { var id = context.GetArgument <int>("id"); var score = context.GetArgument <string>("score"); var team1 = context.GetArgument <string>("team1"); var team2 = context.GetArgument <string>("team2"); if (id == 0 && score == null && team1 == null && team2 == null) { return(i => true); } return(i => (team1 != null && i.Team1 == team1) || (team2 != null && i.Team2 == team2) || (score != null && i.Score == score) || (id != 0 && i.Id == id)); }
private async Task <object> InviteUser(IResolveFieldContext <object> ctx) { var backofficeGrain = _clusterClient.GetGrain <IBackofficeGrain>(Guid.Empty, "backoffice"); var cmd = ctx.GetArgument <InviteUserCmd>("cmd"); var response = await backofficeGrain.InviteUser(cmd.OrganisationId, cmd.UserId, cmd.UserEmail, cmd.UserName); return(response); }
private async ValueTask <IObservable <Message> > SubscribeByIdAsync(IResolveFieldContext context) { var id = context.GetArgument <string>("id"); var messages = await _chat.MessagesAsync().ConfigureAwait(false); return(messages.Where(message => message.From.Id == id)); }
private object ResolveObjectFromGlobalId(IResolveFieldContext <object> context) { var globalId = context.GetArgument <string>("id"); var parts = Node.FromGlobalId(globalId); var node = (IRelayNode <object>)context.Schema.FindType(parts.Type); return(node.GetById(parts.Id)); }
private IObservable <Message> SubscribeById(IResolveFieldContext context) { var id = context.GetArgument <string>("id"); var messages = _chat.Messages(); return(messages.Where(message => message.From.Id == id)); }
/// <summary> /// Wraps <see cref="ResolveFieldContextExtensions.GetArgument{TType}"/> to validate the resulting argument instance. /// Uses <see cref="IValidator.Validate(IValidationContext)"/> to perform validation. /// If a <see cref="ValidationException"/> occurs it will be converted to <see cref="ExecutionError"/>s by a field middleware. /// </summary> public static object GetValidatedArgument(this IResolveFieldContext context, Type argumentType, string name, object?defaultValue = null) { Guard.AgainstNull(context, nameof(context)); var argument = context.GetArgument(argumentType, name, defaultValue); var validatorCache = context.GetCache(); ArgumentValidation.Validate(validatorCache, argumentType, argument, context.UserContext, context.Schema as IServiceProvider); return(argument); }
/// <summary> /// Wraps <see cref="ResolveFieldContextExtensions.GetArgument{TType}"/> to validate the resulting argument instance. /// Uses <see cref="IValidator.ValidateAsync(ValidationContext,CancellationToken)"/> to perform validation. /// If a <see cref="ValidationException"/> it will be converted <see cref="ExecutionError"/>s by a field middleware. /// </summary> public static async Task <TArgument> GetValidatedArgumentAsync <TArgument>(this IResolveFieldContext context, string name, TArgument defaultValue = default) { Guard.AgainstNull(context, nameof(context)); var argument = context.GetArgument(name, defaultValue); var validatorCache = context.GetCache(); await ArgumentValidation.ValidateAsync(validatorCache, typeof(TArgument), argument, context.UserContext); return(argument); }
private async Task <Object> AddReview(IResolveFieldContext <Object> context) { var review = await CreateReview(context.GetArgument <ReviewDto> (reviewArg)).ConfigureAwait(false); await _reviewRepo.Add(review).ConfigureAwait(false); _messageService.AddReviewAddedMessage(review); return(review); }
/// <summary> /// Wraps <see cref="ResolveFieldContextExtensions.GetArgument{TType}"/> to validate the resulting argument instance. /// Uses <see cref="IValidator.Validate(ValidationContext)"/> to perform validation. /// If a <see cref="ValidationException"/> occurs it will be converted to <see cref="ExecutionError"/>s by a field middleware. /// </summary> public static TArgument GetValidatedArgument <TArgument>(this IResolveFieldContext context, string name, TArgument defaultValue = default) { Guard.AgainstNull(context, nameof(context)); var argument = context.GetArgument(name, defaultValue); var validatorCache = context.GetCache(); ArgumentValidation.Validate(validatorCache, typeof(TArgument), argument, context.UserContext, context.Schema as IServiceProvider); return(argument); }
private async Task <object> CreateTenant(IResolveFieldContext <object> ctx) { var backofficeGrain = _clusterClient.GetGrain <IBackofficeGrain>(Guid.Empty, "backoffice"); var cmd = ctx.GetArgument <CreateTenantCmd>("cmd"); var response = await backofficeGrain.CreateTenantAndAdmin(cmd.OrganisationId, cmd.TenantName, cmd.Description, cmd.AdminEmail, cmd.AdminName, cmd.UserId); return(response); }
/// <summary> /// Wraps <see cref="ResolveFieldContextExtensions.GetArgument{TType}"/> to validate the resulting argument instance. /// Uses <see cref="IValidator.ValidateAsync(ValidationContext,CancellationToken)"/> to perform validation. /// If a <see cref="ValidationException"/> it will be converted <see cref="ExecutionError"/>s by a field middleware. /// </summary> public static async Task <object> GetValidatedArgumentAsync(this IResolveFieldContext context, Type argumentType, string name, object?defaultValue = null) { Guard.AgainstNull(context, nameof(context)); var argument = context.GetArgument(argumentType, name, defaultValue); var validatorCache = context.GetCache(); await ArgumentValidation.ValidateAsync(validatorCache, argumentType, argument, context.UserContext); return(argument); }
public object Resolve(IResolveFieldContext context) { var queryable = _dbContext.Query(_tableMetadata.AssemblyFullName); // Get filters var filters = context.Arguments.Where(c => c.Key != "first" && c.Key != "offset"); string predicates = string.Empty; object[] args = new object[filters.Count()]; int paramsCount = -1; foreach (var item in filters) { paramsCount++; if (!string.IsNullOrEmpty(predicates)) { predicates += " and "; } args[paramsCount] = item.Value; // Note: check for like function https://github.com/StefH/System.Linq.Dynamic.Core/issues/105 predicates += $"{item.Key.ToTitleCase()} == @{paramsCount}"; } if (context.FieldName.Contains("_list")) { var first = context.Arguments["first"] != null? context.GetArgument("first", int.MaxValue) : int.MaxValue; var offset = context.Arguments["offset"] != null? context.GetArgument("offset", 0) : 0; if (paramsCount >= 0) { queryable = queryable.Where(predicates, args); } return(queryable.Skip(offset).Take(first).ToDynamicList <object>()); } else { return(paramsCount >= 0 ? queryable.FirstOrDefault(predicates, args) : null); } }
public static IQueryable <TItem> ApplyGraphQlArguments <TItem>( this IQueryable <TItem> queryable, IResolveFieldContext context, List <string>?keyNames, bool applyOrder) where TItem : class { Guard.AgainstNull(nameof(queryable), queryable); Guard.AgainstNull(nameof(context), context); object?GetArguments(Type type, string x) => context.GetArgument(type, x); if (keyNames != null) { if (ArgumentReader.TryReadIds(GetArguments, out var values)) { var keyName = GetKeyName(keyNames); var predicate = ExpressionBuilder <TItem> .BuildPredicate(keyName, Comparison.In, values); queryable = queryable.Where(predicate); } if (ArgumentReader.TryReadId(GetArguments, out var value)) { var keyName = GetKeyName(keyNames); var predicate = ExpressionBuilder <TItem> .BuildPredicate(keyName, Comparison.Equal, new[] { value }); queryable = queryable.Where(predicate); } } if (ArgumentReader.TryReadWhere(GetArguments, out var wheres)) { var predicate = ExpressionBuilder <TItem> .BuildPredicate(wheres); queryable = queryable.Where(predicate); } if (applyOrder) { queryable = Order(queryable, GetArguments); if (ArgumentReader.TryReadSkip(GetArguments, out var skip)) { queryable = queryable.Skip(skip); } if (ArgumentReader.TryReadTake(GetArguments, out var take)) { queryable = queryable.Take(take); } } return(queryable); }