コード例 #1
0
        public async Task <UserComic> CreateUserComic(IResolverContext context)
        {
            Comic            comicInput       = context.Argument <Comic> ("comic");
            StorageContainer storageContainer = context
                                                .Argument <StorageContainer>("storageContainer");

            string userId = context.Argument <string> ("userId");

            if (comicInput is null)
            {
                throw new System.ArgumentNullException(nameof(comicInput));
            }

            _logger.LogDebug("Executing mutation with comic titled: {title}", comicInput.Title);

            UserComic response = await _comicApiRepository.CreateUserComic(
                comicInput,
                storageContainer,
                userId);

            if (response is null)
            {
                throw new CreateComicException($"Unable to add comic {comicInput.Id} for user {userId}");
            }

            return(response);
        }
コード例 #2
0
        public async Task <bool> DeleteUserComic(IResolverContext context)
        {
            string userComicId = context.Argument <string>("userComicId");
            string userId      = context.Argument <string>("userId");
            bool   isDeleted   = await _comicApiRepository.DeleteUserComic(userComicId, userId);

            return(isDeleted);
        }
コード例 #3
0
        public static async Task <IEnumerable <Comment> > GetComments(IResolverContext context)
        {
            var post = context.Parent <Post>();

            var first  = context.Argument <int>("first");
            var offset = context.Argument <int>("offset");

            return(await context
                   .Service <ICommentQuery>()
                   .WithPost(post.CanonicalTitle)
                   .Fetch(first, offset));
        }
コード例 #4
0
        public static IDictionary <string, object> GetCursorProperties(
            this IResolverContext context)
        {
            string cursor = context.Argument <string>("after")
                            ?? context.Argument <string>("before");

            if (cursor == null)
            {
                return(new Dictionary <string, object>());
            }

            return(Base64Serializer
                   .Deserialize <Dictionary <string, object> >(cursor));
        }
コード例 #5
0
ファイル: Extensions.cs プロジェクト: lanicon/modernstore
        public static GraphQueryBase <TDto> ExtractParams <TDto>(this GraphQueryBase <TDto> request,
                                                                 IResolverContext context)
        {
            var page       = context.Argument <int>("page") <= 0 ? 1 : context.Argument <int>("page");
            var pageSize   = context.Argument <int>("pageSize") <= 0 ? 20 : context.Argument <int>("pageSize");
            var filterExpr = context.GetQueryableFilterExpr <TDto>();
            var sortExpr   = context.GetQueryableSortExpr <TDto>();

            request.Page           = page;
            request.PageSize       = pageSize;
            request.FilterExpr     = filterExpr;
            request.SortingVisitor = sortExpr;

            return(request);
        }
        public async Task <bool> HandleAsync <TCommand>(IResolverContext context, CancellationToken token)
        {
            try
            {
                var httpContext = (HttpContext)context.ContextData[nameof(HttpContext)];

                var headers = new Dictionary <string, string>();
                foreach (var header in  httpContext.Request.Headers)
                {
                    headers.Add(header.Key, header.Value.FirstOrDefault());
                }

                using (var _ = AnalyticsService.StartRequestOperation(this, typeof(TCommand).Name, headers))
                {
                    var command = context.Argument <TCommand>("command");
                    if (command == null)
                    {
                        throw new ArgumentException("Unable to extract command from resolver context");
                    }

                    AnalyticsService.TraceVerbose(this, $"{typeof(TCommand).Name} received", command.ToObjectDictionary());

                    var commandResult = await HandleCommandAsync <TCommand>(context, command, token);

                    if (commandResult.IsFailure)
                    {
                        context.ReportError(new ErrorBuilder().SetMessage(commandResult.Error.ToString()).Build());
                        return(default);
コード例 #7
0
ファイル: Extensions.cs プロジェクト: lanicon/modernstore
        public static Expression <Func <TDto, bool> > GetQueryableFilterExpr <TDto>(this IResolverContext context)
        {
            Expression <Func <TDto, bool> > filter = null;

            if (context.Field?.Arguments["where"]?.Type is InputObjectType whereIot &&
                whereIot is IFilterInputType whereFit)
            {
                var whereValueNode = context.Argument <IValueNode>("where");
                if (whereValueNode != null)
                {
                    var queryableFilterVisitor = new QueryableFilterVisitor(
                        whereIot,
                        whereFit.EntityType,
                        TypeConversion.Default);

                    if (whereValueNode.Kind != NodeKind.NullValue)
                    {
                        whereValueNode.Accept(queryableFilterVisitor);
                        filter = queryableFilterVisitor?.CreateFilter <TDto>();
                    }
                }
            }

            return(filter);
        }
コード例 #8
0
        public async Task <IEnumerable <Owner> > GetOwnersByAddress(string address, IResolverContext context)
        {
            IDataLoader <string, Owner[]> ownerDataLoader =
                context.GroupDataLoader <string, Owner>(
                    "ownersByAddress",
                    _ownerRepository.GetOwnersByAddress);

            return(await ownerDataLoader.LoadAsync(context.Argument <string>("address")));
        }
コード例 #9
0
ファイル: Mutation.cs プロジェクト: dessert-wasm/back
        public Task <IUser> UpdateUser([Service] IResolverContext context, [Service] IMediator mediator)
        {
            var input = context.Argument <ApplicationUser>("account");

            return(mediator.Send(new UpdateMyAccountCommand()
            {
                Nickname = input.Nickname,
                ProfilePicUrl = input.ProfilePicUrl,
            }));
        }
コード例 #10
0
        public static double GetHeight(
            IResolverContext context)
        {
            double height = context.Parent <ICharacter>().Height;

            if (context.Argument <Unit?>("unit") == Unit.Foot)
            {
                return(height * 3.28084d);
            }
            return(height);
        }
コード例 #11
0
        public async Task <StorageContainer> CreateStorageContainer(IResolverContext context)
        {
            var storageContainerArgument = context.Argument <StorageContainer>("storageContainer");

            StorageContainer storageContainer = await _storageContainerHttpRepository
                                                .CreateStorageContainer(storageContainerArgument);

            _logger.LogDebug("Saved '{storageContainerLabel}' to ComicEngine Api - ID '{storageContainerId}'",
                             storageContainer.Label,
                             storageContainer.Id);

            return(storageContainer);
        }
コード例 #12
0
        public async Task <Participant> CreateParticipantSubmission([Service] RorschachContext rorschachContext,
                                                                    [Service] IResolverContext resolverContext)
        {
            InputParticipantSubmission input =
                resolverContext.Argument <InputParticipantSubmission>("participantSubmission");

            if (input == null)
            {
                throw new Exception(
                          "Error: Participant submission object was null. Data cannot be processed as a result.");
            }


            Participant participant = await rorschachContext.Participants.Where(x => x.ID == input.ID).FirstAsync();

            if (participant.EndTime != null)
            {
                throw new Exception(
                          "Error: Participant identified in the submission has already completed the survey. ");
            }
            if (participant == null)
            {
                throw new Exception(
                          "Error: Participant identified in the submission could not be found within the data source. ");
            }
            int totalQuestions = await rorschachContext.Questions.CountAsync();

            if (input.Responses.Count != totalQuestions)
            {
                throw new Exception($"Error: An incorrect number of responses were submitted for processed. " +
                                    $"The correct number to use is {totalQuestions}.");
            }
            List <Response> responses = new List <Response>();

            foreach (var response in input.Responses)
            {
                Response holder = new Response()
                {
                    ParticipantID = input.ID,
                    QuestionID    = response.QuestionId,
                    Text          = response.Text
                };
                responses.Add(holder);
            }

            participant.Responses = responses;
            participant.EndTime   = DateTime.UtcNow;
            await rorschachContext.SaveChangesAsync();

            return(participant);
        }
コード例 #13
0
        public VariableValue Resolve(
            IResolverContext context,
            ScopedVariableNode variable,
            ITypeNode targetType)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

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

            if (!ScopeNames.Arguments.Equals(variable.Scope.Value))
            {
                throw new ArgumentException(StitchingResources
                                            .ArgumentScopedVariableResolver_CannotHandleVariable,
                                            nameof(variable));
            }

            IInputField argument = context.Field.Arguments.FirstOrDefault(t =>
                                                                          t.Name.Value.EqualsOrdinal(variable.Name.Value));

            if (argument == null)
            {
                throw new QueryException(QueryError.CreateFieldError(
                                             string.Format(CultureInfo.InvariantCulture,
                                                           StitchingResources
                                                           .ArgumentScopedVariableResolver_InvalidArgumentName,
                                                           variable.Name.Value),
                                             context.Path,
                                             context.FieldSelection)
                                         .WithCode(ErrorCodes.ArgumentNotDefined));
            }

            return(new VariableValue
                   (
                       variable.ToVariableName(),
                       argument.Type.ToTypeNode(),
                       context.Argument <object>(variable.Name.Value),
                       argument.Type.IsNonNullType() &&
                       argument.DefaultValue.IsNull()
                    ? null
                    : argument.DefaultValue
                   ));
        }
コード例 #14
0
        public VariableValue Resolve(
            IResolverContext context,
            ScopedVariableNode variable,
            IInputType targetType)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

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

            if (!ScopeNames.Arguments.Equals(variable.Scope.Value))
            {
                throw new ArgumentException(
                          StitchingResources.ArgumentScopedVariableResolver_CannotHandleVariable,
                          nameof(variable));
            }

            IInputField argument = context.Field.Arguments.FirstOrDefault(t =>
                                                                          t.Name.Value.EqualsOrdinal(variable.Name.Value));

            if (argument == null)
            {
                throw new QueryException(ErrorBuilder.New()
                                         .SetMessage(
                                             StitchingResources.ArgumentScopedVariableResolver_InvalidArgumentName,
                                             variable.Name.Value)
                                         .SetCode(ErrorCodes.ArgumentNotDefined)
                                         .SetPath(context.Path)
                                         .AddLocation(context.FieldSelection)
                                         .Build());
            }

            return(new VariableValue
                   (
                       variable.ToVariableName(),
                       argument.Type.ToTypeNode(),
                       context.Argument <IValueNode>(variable.Name.Value),
                       argument.Type.IsNonNullType() && argument.DefaultValue.IsNull()
                    ? null
                    : argument.DefaultValue
                   ));
        }
        public void Validate(IResolverContext context)
        {
            foreach (InputField argument in context.Field.Arguments)
            {
                foreach (IDirective directive in argument.Directives)
                {
                    object argumentValue =
                        context.Argument <object>(argument.Name);

                    var argumentValidator =
                        directive.ToObject <ArgumentValidationDirective>();

                    argumentValidator.Validator(
                        directive, context.FieldSelection, argumentValue);
                }
            }
        }
コード例 #16
0
ファイル: Extensions.cs プロジェクト: lanicon/modernstore
        public static QueryableSortVisitor GetQueryableSortExpr <TDto>(this IResolverContext context)
        {
            QueryableSortVisitor queryableSortVisitor = null;

            if (context.Field?.Arguments[SortObjectFieldDescriptorExtensions.OrderByArgumentName]?.Type is
                InputObjectType iot &&
                iot is ISortInputType fit)
            {
                var orderByValueNode =
                    context.Argument <IValueNode>(SortObjectFieldDescriptorExtensions.OrderByArgumentName);
                if (orderByValueNode != null)
                {
                    queryableSortVisitor = new QueryableSortVisitor(iot, fit.EntityType);
                    orderByValueNode.Accept(queryableSortVisitor);
                }
            }

            return(queryableSortVisitor);
        }
コード例 #17
0
ファイル: Mutation.cs プロジェクト: dessert-wasm/back
        public Task <Module> CreateModule([Service] IResolverContext context,
                                          [Service] IMediator mediator,
                                          string token,
                                          string name,
                                          string description,
                                          string githubLink,
                                          bool isCore)
        {
            var replacements = context.Argument <IEnumerable <ModuleReplacement> >("replacements");

            return(mediator.Send(new CreateModule
            {
                Description = description,
                Name = name,
                Replacements = replacements.ToArray(),
                Token = token,
                GithubLink = githubLink,
                IsCore = isCore
            }));
        }
コード例 #18
0
        // Note that only the necessary mutations will be created as a preventative measure for the web application
        // Given that there is no need for user's to be able to input new cards, choices, questions, etc.
        // the only inputs that will be available are for the insertion of new participants as well as the insertion of their respective responses
        // Note that participants that have already taken the exam and mention this explicitly will be denied and that participants that have taken the test
        // on a device with an IP already in the system will be put on a timed wait-list (15 minutes)

        public async Task <Participant> CreateParticipant([Service] RorschachContext rorschachContext,
                                                          [Service] IResolverContext context, [Service] IHttpContextAccessor clientHttpContext
                                                          )
        {
            InputParticipant input = context.Argument <InputParticipant>("participant");
            var participant        = new Participant()
            {
                Honest       = input.Honest,
                FirstAttempt = input.FirstAttempt,
                Consent      = input.Consent,
                Name         = string.IsNullOrEmpty(input.Name) ? "ANONYMOUS" : input.Name.ToUpper(),
                AgeRange     = input.AgeRange,
                Occupation   = input.Occupation,
                StartTime    = DateTime.UtcNow,
                EndTime      = null,
                IpAddress    = clientHttpContext.HttpContext.Connection.RemoteIpAddress.ToString()
            };
            await rorschachContext.Participants.AddAsync(participant);

            await rorschachContext.SaveChangesAsync();

            return(participant);
        }
コード例 #19
0
 public T Argument <T>(string name) =>
 _resolverContext.Argument <T>(name);
コード例 #20
0
 public void ResolverContext(IResolverContext context)
 {
     Id = context.Argument <int>("id");
 }
コード例 #21
0
 public void ResolverContext(IResolverContext context)
 {
     _context = context;
     Id       = context.Parent <Property>().Id;
     Last     = context.Argument <int?>("last");
 }
コード例 #22
0
 public void ResolverContext(IResolverContext context)
 {
     _context   = context;
     Descending = context.Argument <bool>("descending");
 }
コード例 #23
0
 public static PaginationQuery GetPaginationQuery(this IResolverContext context)
 {
     return(context.Argument <PaginationQuery>(PaginationArgumentName));
 }
コード例 #24
0
 public void ResolverContext(IResolverContext context)
 {
     Last = context.Argument <int?>("last");
 }