Exemple #1
0
        private static ObjectFieldDefinition CreateDefinition(
            IDescriptorContext context)
        {
            var descriptor = ObjectFieldDescriptor
                             .New(context, "node");

            descriptor
            .Argument("id", a => a.Type <NonNullType <IdType> >())
            .Type <NonNullType <NodeType> >()
            .Resolver(async ctx =>
            {
                string id = ctx.Argument <string>("id");
                IdValue deserializedId = _idSerializer.Deserialize(id);

                if (ctx.Schema.TryGetType(deserializedId.TypeName,
                                          out ObjectType type) &&
                    type.ContextData.TryGetValue(
                        RelayConstants.NodeResolverFactory,
                        out object o) &&
                    o is Func <IServiceProvider, INodeResolver> factory)
                {
                    INodeResolver resolver =
                        factory.Invoke(ctx.Service <IServiceProvider>());

                    return(await resolver.ResolveAsync(
                               ctx, deserializedId.Value)
                           .ConfigureAwait(false));
                }

                return(null);
            });

            return(descriptor.CreateDefinition());
        }
        public void DeserializeIdValue(
            string serialized, object id, Type idType)
        {
            // arrange
            var serializer = new IdSerializer();

            // act
            IdValue value = serializer.Deserialize(serialized);

            // assert
            Assert.IsType(idType, value.Value);
            Assert.Equal(id, value.Value);
            Assert.Equal("Foo", value.TypeName);
        }
        public override void OnBeforeCompleteType(
            ITypeCompletionContext completionContext,
            DefinitionBase definition,
            IDictionary <string, object> contextData)
        {
            if ((completionContext.IsQueryType ?? false) &&
                definition is ObjectTypeDefinition objectTypeDefinition)
            {
                ObjectFieldDefinition typeNameField = objectTypeDefinition.Fields.First(
                    t => t.Name.Equals(IntrospectionFields.TypeName) && t.IsIntrospectionField);
                var index = objectTypeDefinition.Fields.IndexOf(typeNameField) + 1;

                var descriptor = ObjectFieldDescriptor.New(
                    completionContext.DescriptorContext,
                    _node);

                IIdSerializer serializer =
                    completionContext.Services.GetService <IIdSerializer>() ??
                    new IdSerializer();

                descriptor
                .Argument(_id, a => a.Type <NonNullType <IdType> >())
                .Type <NodeType>()
                .Resolve(async ctx =>
                {
                    var id = ctx.ArgumentValue <string>(_id);
                    IdValue deserializedId = serializer.Deserialize(id);

                    ctx.LocalContextData = ctx.LocalContextData
                                           .SetItem(WellKnownContextData.Id, deserializedId.Value)
                                           .SetItem(WellKnownContextData.Type, deserializedId.TypeName);

                    if (ctx.Schema.TryGetType(deserializedId.TypeName,
                                              out ObjectType type) &&
                        type.ContextData.TryGetValue(
                            RelayConstants.NodeResolverFactory,
                            out object?o) &&
                        o is Func <IServiceProvider, INodeResolver> factory)
                    {
                        INodeResolver resolver = factory.Invoke(ctx.Services);
                        return(await resolver.ResolveAsync(ctx, deserializedId.Value)
                               .ConfigureAwait(false));
                    }

                    return(null);
                });

                objectTypeDefinition.Fields.Insert(index, descriptor.CreateDefinition());
            }
        }
        public void DeserializeGuidValue()
        {
            // arrange
            var serialized = "Rm9vCmdkYWQ0ZjMzZDMwMzM0NWQ3Yjc1NDFkOWFjMjM5NzRkOQ==";
            var serializer = new IdSerializer();

            // act
            IdValue value = serializer.Deserialize(serialized);

            // assert
            Assert.Equal(
                new Guid("dad4f33d303345d7b7541d9ac23974d9"),
                Assert.IsType <Guid>(value.Value));
            Assert.Equal("Foo", value.TypeName);
        }
        public void DeserializeGuidValue()
        {
            // arrange
            var serialized = "Rm9vLWc989TaMzDXRbdUHZrCOXTZ";
            var serializer = new IdSerializer();

            // act
            IdValue value = serializer.Deserialize(serialized);

            // assert
            Assert.Equal(
                new Guid("dad4f33d303345d7b7541d9ac23974d9"),
                Assert.IsType <Guid>(value.Value));
            Assert.Equal("Foo", value.TypeName);
        }
Exemple #6
0
        private static ObjectFieldDefinition CreateDefinition(
            IDescriptorContext context)
        {
            var descriptor = ObjectFieldDescriptor
                             .New(context, _node);

            IIdSerializer _serializer = null;

            descriptor
            .Argument(_id, a => a.Type <NonNullType <IdType> >())
            .Type <NonNullType <NodeType> >()
            .Resolver(async ctx =>
            {
                IServiceProvider services = ctx.Service <IServiceProvider>();

                if (_serializer is null)
                {
                    _serializer =
                        services.GetService(typeof(IIdSerializer)) is IIdSerializer s
                                ? s
                                : new IdSerializer();
                }

                var id = ctx.Argument <string>(_id);
                IdValue deserializedId = _serializer.Deserialize(id);

                ctx.LocalContextData = ctx.LocalContextData
                                       .SetItem(WellKnownContextData.Id, deserializedId.Value)
                                       .SetItem(WellKnownContextData.Type, deserializedId.TypeName);

                if (ctx.Schema.TryGetType(deserializedId.TypeName,
                                          out ObjectType type) &&
                    type.ContextData.TryGetValue(
                        RelayConstants.NodeResolverFactory,
                        out var o) &&
                    o is Func <IServiceProvider, INodeResolver> factory)
                {
                    INodeResolver resolver = factory.Invoke(services);
                    return(await resolver.ResolveAsync(ctx, deserializedId.Value)
                           .ConfigureAwait(false));
                }

                return(null);
            });

            return(descriptor.CreateDefinition());
        }
Exemple #7
0
        public override void OnBeforeCompleteType(
            ITypeCompletionContext completionContext,
            DefinitionBase?definition,
            IDictionary <string, object?> contextData)
        {
            if ((completionContext.IsQueryType ?? false) &&
                definition is ObjectTypeDefinition objectTypeDefinition)
            {
                ObjectFieldDefinition typeNameField = objectTypeDefinition.Fields.First(
                    t => t.Name.Equals(IntrospectionFields.TypeName) && t.IsIntrospectionField);
                var index = objectTypeDefinition.Fields.IndexOf(typeNameField) + 1;

                var descriptor = ObjectFieldDescriptor.New(
                    completionContext.DescriptorContext,
                    Node);

                IIdSerializer serializer =
                    completionContext.Services.GetService <IIdSerializer>() ??
                    new IdSerializer();

                descriptor
                .Argument(Id, a => a.Type <NonNullType <IdType> >().ID())
                .Type <NodeType>()
                .Resolve(async ctx =>
                {
                    StringValueNode id     = ctx.ArgumentLiteral <StringValueNode>(Id);
                    IdValue deserializedId = serializer.Deserialize(id.Value);

                    ctx.SetLocalValue(NodeId, id.Value);
                    ctx.SetLocalValue(InternalId, deserializedId.Value);
                    ctx.SetLocalValue(InternalType, deserializedId.TypeName);
                    ctx.SetLocalValue(WellKnownContextData.IdValue, deserializedId);

                    if (ctx.Schema.TryGetType(deserializedId.TypeName, out ObjectType type) &&
                        type.ContextData.TryGetValue(NodeResolver, out object?o) &&
                        o is FieldResolverDelegate resolver)
                    {
                        return(await resolver.Invoke(ctx).ConfigureAwait(false));
                    }

                    return(null);
                });

                objectTypeDefinition.Fields.Insert(index, descriptor.CreateDefinition());
            }
        }
        private static async ValueTask <object?> ResolveSingleNode(
            IResolverContext context,
            IIdSerializer serializer,
            NameString argumentName)
        {
            StringValueNode nodeId         = context.ArgumentLiteral <StringValueNode>(argumentName);
            IdValue         deserializedId = serializer.Deserialize(nodeId.Value);
            NameString      typeName       = deserializedId.TypeName;

            context.SetLocalValue(NodeId, nodeId.Value);
            context.SetLocalValue(InternalId, deserializedId.Value);
            context.SetLocalValue(InternalType, typeName);
            context.SetLocalValue(WellKnownContextData.IdValue, deserializedId);

            if (context.Schema.TryGetType <ObjectType>(typeName, out var type) &&
                type.ContextData.TryGetValue(NodeResolver, out var o) &&
                o is FieldResolverDelegate resolver)
            {
                return(await resolver.Invoke(context).ConfigureAwait(false));
            }

            return(null);
        }
        private static async ValueTask <object?> ResolveManyNode(
            IResolverContext context,
            IIdSerializer serializer)
        {
            if (context.ArgumentKind(Ids) == ValueKind.List)
            {
                ListValueNode    list  = context.ArgumentLiteral <ListValueNode>(Ids);
                Task <object?>[] tasks = ArrayPool <Task <object?> > .Shared.Rent(list.Items.Count);

                var result = new object?[list.Items.Count];

                try
                {
                    for (var i = 0; i < list.Items.Count; i++)
                    {
                        context.RequestAborted.ThrowIfCancellationRequested();

                        // it is guaranteed that this is always a string literal.
                        StringValueNode nodeId         = (StringValueNode)list.Items[i];
                        IdValue         deserializedId = serializer.Deserialize(nodeId.Value);
                        NameString      typeName       = deserializedId.TypeName;

                        context.SetLocalValue(NodeId, nodeId.Value);
                        context.SetLocalValue(InternalId, deserializedId.Value);
                        context.SetLocalValue(InternalType, typeName);
                        context.SetLocalValue(WellKnownContextData.IdValue, deserializedId);

                        tasks[i] =
                            context.Schema.TryGetType <ObjectType>(typeName, out var type) &&
                            type.ContextData.TryGetValue(NodeResolver, out var o) &&
                            o is FieldResolverDelegate resolver
                                ? resolver.Invoke(context).AsTask()
                                : _nullTask;
                    }

                    for (var i = 0; i < list.Items.Count; i++)
                    {
                        context.RequestAborted.ThrowIfCancellationRequested();

                        Task <object?> task = tasks[i];
                        if (task.IsCompleted)
                        {
                            if (task.Exception is null)
                            {
                                result[i] = task.Result;
                            }
                            else
                            {
                                result[i] = null;
                                ReportError(context, i, task.Exception);
                            }
                        }
                        else
                        {
                            try
                            {
                                result[i] = await task;
                            }
                            catch (Exception ex)
                            {
                                result[i] = null;
                                ReportError(context, i, ex);
                            }
                        }
                    }

                    return(result);
                }
                finally
                {
                    ArrayPool <Task <object?> > .Shared.Return(tasks);
                }
            }
            else
            {
                var result = new object?[1];
                result[0] = await ResolveSingleNode(context, serializer, Ids);

                return(result);
            }
        }
        public object?OnAfterDeserialize(object?runtimeValue)
        {
            if (runtimeValue is null)
            {
                return(null);
            }

            if (runtimeValue is IdValue v)
            {
                if (!_validateType || _typeName.Equals(v.TypeName))
                {
                    return(v.Value);
                }
            }

            if (runtimeValue is string s)
            {
                try
                {
                    IdValue id = _idSerializer.Deserialize(s);

                    if (!_validateType || _typeName.Equals(id.TypeName))
                    {
                        return(id.Value);
                    }
                }
                catch
                {
                    throw new GraphQLException(
                              ErrorBuilder.New()
                              .SetMessage("The ID `{0}` has an invalid format.", s)
                              .Build());
                }

                throw new GraphQLException(
                          ErrorBuilder.New()
                          .SetMessage("The ID `{0}` is not an ID of `{1}`.", s, _typeName)
                          .Build());
            }

            if (runtimeValue is IEnumerable <string> stringEnumerable)
            {
                try
                {
                    IList list = _createList();

                    foreach (string sv in stringEnumerable)
                    {
                        IdValue id = _idSerializer.Deserialize(sv);

                        if (!_validateType || _typeName.Equals(id.TypeName))
                        {
                            list.Add(id.Value);
                        }
                    }

                    return(list);
                }
                catch
                {
                    throw new GraphQLException(
                              ErrorBuilder.New()
                              .SetMessage(
                                  "The IDs `{0}` have an invalid format.",
                                  string.Join(", ", stringEnumerable))
                              .Build());
                }
            }

            throw new GraphQLException(
                      ErrorBuilder.New()
                      .SetMessage("The specified value is not a valid ID value.")
                      .Build());
        }