internal static IValueNode?CompleteDefaultValue( ITypeCompletionContext context, ArgumentDefinition argumentDefinition, IInputType argumentType, FieldCoordinate argumentCoordinate) { try { return(argumentDefinition.RuntimeDefaultValue != null ? context.DescriptorContext.InputFormatter.FormatValue( argumentDefinition.RuntimeDefaultValue, argumentType, Path.Root) : argumentDefinition.DefaultValue); } catch (Exception ex) { context.ReportError(SchemaErrorBuilder.New() .SetMessage( TypeResources.FieldInitHelper_InvalidDefaultValue, argumentCoordinate) .SetCode(ErrorCodes.Schema.MissingType) .SetTypeSystemObject(context.Type) .AddSyntaxNode(argumentDefinition.SyntaxNode) .SetException(ex) .Build()); return(NullValueNode.Default); } }
public static IValueNode CreateDefaultValue( ICompletionContext context, ArgumentDefinition definition, IInputType fieldType) { try { if (definition.NativeDefaultValue != null) { return(fieldType.ParseValue( definition.NativeDefaultValue)); } return(definition.DefaultValue.IsNull() ? NullValueNode.Default : definition.DefaultValue); } catch (Exception ex) { context.ReportError(SchemaErrorBuilder.New() .SetMessage(TypeResources.FieldInitHelper_InvalidDefaultValue) .SetCode(TypeErrorCodes.MissingType) .SetTypeSystemObject(context.Type) .AddSyntaxNode(definition.SyntaxNode) .SetException(ex) .Build()); return(NullValueNode.Default); } }
public static SchemaException FilterConvention_OperationNameNotFound(int operation) => new SchemaException( SchemaErrorBuilder.New() .SetMessage( DataResources.FilterConvention_OperationNameNotFound, operation) .Build());
private void CollectErrors() { foreach (InitializationContext context in _registeredTypes.Values.Distinct().Select(t => t.InitializationContext)) { _errors.AddRange(context.Errors); } IReadOnlyCollection <ITypeReference> unresolved = _typeRegistrar.GetUnresolved(); if (_errors.Count == 0 && unresolved.Count > 0) { foreach (IClrTypeReference unresolvedReference in _typeRegistrar.GetUnresolved()) { _errors.Add(SchemaErrorBuilder.New() .SetMessage( TypeResources.TypeRegistrar_TypesInconsistent, unresolvedReference) .SetExtension( TypeErrorFields.Reference, unresolvedReference) .SetCode(ErrorCodes.Schema.UnresolvedTypes) .Build()); } } }
public IPublishSchemaDefinitionDescriptor AddTypeExtensionsFromResource( Assembly assembly, string key) { _builder.ConfigureSchemaAsync( async(s, ct) => { Stream?stream = assembly.GetManifestResourceStream(key); if (stream is null) { // todo : throw helper throw new SchemaException( SchemaErrorBuilder.New() .SetMessage( "The resource `{0}` was not found!", key) .Build()); } using (stream) { var buffer = new byte[stream.Length]; await stream.ReadAsync(buffer, 0, buffer.Length, ct).ConfigureAwait(false); s.AddTypeExtensions(Utf8GraphQLParser.Parse(buffer), _key); } }); return(this); }
private static void AddSerializerToInputField( ITypeCompletionContext completionContext, ArgumentDefinition definition, NameString typeName) { ITypeInspector typeInspector = completionContext.TypeInspector; IExtendedType? resultType; if (definition is InputFieldDefinition inputField) { resultType = typeInspector.GetReturnType(inputField.Property !, true); } else if (definition.Parameter is not null) { resultType = typeInspector.GetArgumentType(definition.Parameter, true); } else if (definition.Type is ExtendedTypeReference typeReference) { resultType = typeReference.Type; } else { throw new SchemaException(SchemaErrorBuilder.New() .SetMessage("Unable to resolve type from field `{0}`.", definition.Name) .SetTypeSystemObject(completionContext.Type) .Build()); } definition.Formatters.Add(CreateSerializer(completionContext, resultType, typeName)); }
private bool ValidateFields( ICompletionContext context, ObjectTypeDefinition definition) { ObjectFieldDefinition[] invalidFields = definition.Fields.Where(t => t.Type is null).ToArray(); foreach (ObjectFieldDefinition field in invalidFields) { // TODO : resources context.ReportError(SchemaErrorBuilder.New() .SetMessage(string.Format( CultureInfo.InvariantCulture, "Unable to infer or resolve the type of " + "field {0}.{1}. Try to explicitly provide the " + "type like the following: " + "`descriptor.Field(\"field\")" + ".Type<List<StringType>>()`.", Name, field.Name)) .SetCode(ErrorCodes.Schema.NoFieldType) .SetTypeSystemObject(this) .SetPath(Path.New(Name).Append(field.Name)) .SetExtension(TypeErrorFields.Definition, field) .Build()); } return(invalidFields.Length == 0); }
internal sealed override void CompleteName(ITypeCompletionContext context) { AssertInitialized(); TDefinition definition = _definition !; OnBeforeCompleteName(context, definition, definition.ContextData); ExecuteConfigurations(context, definition, ApplyConfigurationOn.Naming); OnCompleteName(context, definition); Debug.Assert( Name.HasValue, "After the naming is completed the name has to have a value."); if (Name.IsEmpty) { context.ReportError(SchemaErrorBuilder.New() .SetMessage( TypeResources.TypeSystemObjectBase_NameIsNull, GetType().FullName) .SetCode(ErrorCodes.Schema.NoName) .SetTypeSystemObject(this) .Build()); } OnAfterCompleteName(context, definition, definition.ContextData); MarkNamed(); }
public static ISchemaError ArgumentNotImplemented( IOutputField field, IOutputField implementedField, IInputField missingArgument) { bool isInterface = field.DeclaringType.Kind == TypeKind.Interface; return(SchemaErrorBuilder.New() .SetMessage( "The argument `{0}` of the implemented field `{1}` must be defined. " + "The field `{2}` must include an argument of the same name for " + "every argument defined on the implemented field " + "of the interface type `{3}`.", missingArgument.Name, field.Name, field.Name, implementedField.DeclaringType.Print()) .SetType(field.DeclaringType) .SetField(field) .SetImplementedField(implementedField) .AddSyntaxNode(missingArgument.SyntaxNode) .SetExtension("missingArgument", missingArgument) .SetSpecifiedBy(isInterface) .Build()); }
private void CompleteTypeSet( ICompletionContext context, UnionTypeDefinition definition) { var typeSet = new HashSet <ObjectType>(); OnCompleteTypeSet(context, definition, typeSet); foreach (ObjectType objectType in typeSet) { _typeMap[objectType.Name] = objectType; } if (typeSet.Count == 0) { // TODO : RESOURCES context.ReportError(SchemaErrorBuilder.New() .SetMessage("A Union type must define one or " + "more unique member types.") .SetCode(TypeErrorCodes.MissingType) .SetTypeSystemObject(this) .AddSyntaxNode(SyntaxNode) .Build()); } }
protected override void OnCompleteType( ITypeCompletionContext context, EnumTypeDefinition definition) { base.OnCompleteType(context, definition); _naming = context.DescriptorContext.Naming; SyntaxNode = definition.SyntaxNode; foreach (EnumValueDefinition enumValueDefinition in definition.Values) { if (TryCreateEnumValue(context, enumValueDefinition, out IEnumValue? enumValue)) { _enumValues[enumValue.Name] = enumValue; _valueLookup[enumValue.Value] = enumValue; } } if (!Values.Any()) { context.ReportError( SchemaErrorBuilder.New() .SetMessage(TypeResources.EnumType_NoValues, Name) .SetCode(ErrorCodes.Schema.NoEnumValues) .SetTypeSystemObject(this) .AddSyntaxNode(SyntaxNode) .Build()); } }
public static void CompleteFields <TTypeDef, TFieldType, TFieldDef>( ICompletionContext context, TTypeDef definition, IReadOnlyCollection <FieldBase <TFieldType, TFieldDef> > fields) where TTypeDef : DefinitionBase, IHasSyntaxNode where TFieldType : IType where TFieldDef : FieldDefinitionBase { if (context.Type is IType type && fields.Count == 0) { string kind = context.Type is IType t ? t.Kind.ToString() : TypeKind.Directive.ToString(); context.ReportError(SchemaErrorBuilder.New() .SetMessage(string.Format( CultureInfo.InvariantCulture, TypeResources.FieldInitHelper_NoFields, kind, context.Type.Name)) .SetCode(TypeErrorCodes.MissingType) .SetTypeSystemObject(context.Type) .AddSyntaxNode(definition.SyntaxNode) .Build()); return; } foreach (FieldBase <TFieldType, TFieldDef> field in fields) { field.CompleteField(context); } }
public static IValueNode CreateDefaultValue( ITypeCompletionContext context, ArgumentDefinition argumentDefinition, IInputType argumentType, FieldCoordinate argumentCoordinate) { try { return(argumentDefinition.NativeDefaultValue != null ? argumentType.ParseValue(argumentDefinition.NativeDefaultValue) : argumentDefinition.DefaultValue); } catch (Exception ex) { context.ReportError(SchemaErrorBuilder.New() .SetMessage( TypeResources.FieldInitHelper_InvalidDefaultValue, argumentCoordinate) .SetCode(ErrorCodes.Schema.MissingType) .SetTypeSystemObject(context.Type) .AddSyntaxNode(argumentDefinition.SyntaxNode) .SetException(ex) .Build()); return(NullValueNode.Default); } }
private static FieldCollection <TField> CompleteFieldsInternal <TField>( ITypeCompletionContext context, ITypeSystemMember declaringMember, TField[] fields) where TField : class, IField { if (declaringMember is IType type && fields.Length == 0) { context.ReportError(SchemaErrorBuilder.New() .SetMessage(string.Format( CultureInfo.InvariantCulture, TypeResources.FieldInitHelper_NoFields, type.Kind.ToString(), context.Type.Name)) .SetCode(ErrorCodes.Schema.MissingType) .SetTypeSystemObject(context.Type) .AddSyntaxNode((type as IHasSyntaxNode)?.SyntaxNode) .Build()); return(FieldCollection <TField> .Empty); } foreach (TField field in fields) { ((IFieldCompletion)field).CompleteField(context, declaringMember); } return(new FieldCollection <TField>(fields)); }
private static ITypeReference RewriteToNonNullableType(ITypeReference type) { if (type is IClrTypeReference clrTypeRef) { Type rewritten = Unwrap(UnwrapNonNull(Unwrap(clrTypeRef.Type))); rewritten = IsListType(rewritten) ? GetInnerListType(rewritten) : clrTypeRef.Type; if (rewritten is null) { throw new SchemaException( SchemaErrorBuilder.New() .SetMessage( "The specified type `{0}` is not valid for SingleOrDefault.", clrTypeRef.Type.ToString()) .Build()); } return(new ClrTypeReference(rewritten, TypeContext.Output)); } throw new NotSupportedException(); }
protected override void OnCompleteType( ICompletionContext context, DirectiveTypeDefinition definition) { base.OnCompleteType(context, definition); _converter = context.Services.GetTypeConversion(); MiddlewareComponents = definition.MiddlewareComponents.ToList().AsReadOnly(); SyntaxNode = definition.SyntaxNode; ClrType = definition.ClrType == GetType() ? typeof(object) : definition.ClrType; IsRepeatable = definition.IsRepeatable; Locations = definition.Locations.ToList().AsReadOnly(); Arguments = new FieldCollection <Argument>( definition.Arguments.Select(t => new Argument(t))); IsExecutable = MiddlewareComponents.Count > 0; if (!Locations.Any()) { // TODO : resources context.ReportError(SchemaErrorBuilder.New() .SetMessage( $"The `{Name}` directive does not declare any " + "location on which it is valid.") .SetCode(TypeErrorCodes.MissingType) .SetTypeSystemObject(context.Type) .AddSyntaxNode(definition.SyntaxNode) .Build()); } FieldInitHelper.CompleteFields(context, definition, Arguments); }
public IReadOnlyList <ISchemaError> DiscoverTypes() { const int max = 1000; var tries = 0; var resolved = false; do { try { tries++; RegisterTypes(); resolved = TryInferTypes(); } catch (SchemaException ex) { _errors.AddRange(ex.Errors); } catch (Exception ex) { _errors.Add(SchemaErrorBuilder.New() .SetMessage(ex.Message) .SetException(ex) .Build()); } }while (resolved && tries < max && _errors.Count == 0); CollectErrors(); return(_errors); }
public static Exception TypeDoesNotExposeErrorFactory(Type errorType) => new SchemaException(SchemaErrorBuilder .New() .SetMessage( MutationResources.ThrowHelper_ErrorFactoryCompiler_TypeDoesNotExposeErrorFactory, errorType.FullName ?? errorType.Name) .Build());
protected override void OnCompleteType( ICompletionContext context, DirectiveTypeDefinition definition) { base.OnCompleteType(context, definition); _converter = context.Services.GetTypeConversion(); MiddlewareComponents = definition.MiddlewareComponents.ToList().AsReadOnly(); SyntaxNode = definition.SyntaxNode; Locations = definition.Locations.ToList().AsReadOnly(); Arguments = new FieldCollection <Argument>( definition.Arguments.Select(t => new Argument(t))); IsExecutable = MiddlewareComponents.Count > 0; if (Locations.Count == 0) { context.ReportError(SchemaErrorBuilder.New() .SetMessage(string.Format( CultureInfo.InvariantCulture, TypeResources.DirectiveType_NoLocations, Name)) .SetCode(ErrorCodes.Schema.MissingType) .SetTypeSystemObject(context.Type) .AddSyntaxNode(definition.SyntaxNode) .Build()); } FieldInitHelper.CompleteFields(context, definition, Arguments); }
public static Exception MessageWasNotDefinedOnError(IType type, Type runtimeType) => new SchemaException(SchemaErrorBuilder.New() .SetMessage( MutationResources.ThrowHelper_ErrorObjectType_MessageWasNotDefinedOnError, type.GetType().FullName, runtimeType.FullName) .Build());
protected override void OnCompleteField( ITypeCompletionContext context, ITypeSystemMember declaringMember, ArgumentDefinition definition) { if (definition.Type is null) { context.ReportError(SchemaErrorBuilder.New() .SetMessage(TypeResources.Argument_TypeIsNull, definition.Name) .SetTypeSystemObject(context.Type) .SetExtension("declaringMember", declaringMember) .SetExtension("name", definition.Name.ToString()) .Build()); return; } base.OnCompleteField(context, declaringMember, definition); Type = context.GetType <IInputType>(definition.Type !); _runtimeType = definition.RuntimeType ?? definition.Parameter?.ParameterType !; _runtimeType = CompleteRuntimeType(Type, _runtimeType, out var isOptional); DefaultValue = CompleteDefaultValue(context, definition, Type, Coordinate); IsOptional = isOptional; DeclaringMember = declaringMember; }
protected override void OnCompleteType( ITypeCompletionContext context, EnumTypeDefinition definition) { base.OnCompleteType(context, definition); SyntaxNode = definition.SyntaxNode; foreach (EnumValue enumValue in definition.Values .Select(t => new EnumValue(t))) { _nameToValues[enumValue.Name] = enumValue; _valueToValues[enumValue.Value] = enumValue; enumValue.CompleteValue(context); } if (!Values.Any()) { context.ReportError( SchemaErrorBuilder.New() .SetMessage(TypeResources.EnumType_NoValues, Name) .SetCode(ErrorCodes.Schema.NoEnumValues) .SetTypeSystemObject(this) .AddSyntaxNode(SyntaxNode) .Build()); } }
public DiscoveredTypes DiscoverTypes() { const int max = 1000; int tries = 0; bool resolved = false; do { try { tries++; RegisterTypes(); resolved = TryInferTypes(); } catch (SchemaException ex) { _errors.AddRange(ex.Errors); } catch (Exception ex) { _errors.Add(SchemaErrorBuilder.New() .SetMessage(ex.Message) .SetException(ex) .Build()); } }while (resolved && tries < max); CollectErrors(); return(new DiscoveredTypes( _registeredTypes, _clrTypeReferences, _errors)); }
private Type GetSchemaType( IDescriptorContext context, MemberInfo member) { Type? type = SchemaType; ITypeReference returnType = context.Inspector.GetReturnType( member, TypeContext.Output); if (type is null && returnType is IClrTypeReference clr && TypeInspector.Default.TryCreate(clr.Type, out var typeInfo)) { if (BaseTypes.IsSchemaType(typeInfo.ClrType)) { type = typeInfo.ClrType; } else if (SchemaTypeResolver.TryInferSchemaType( clr.WithType(typeInfo.ClrType), out IClrTypeReference schemaType)) { type = schemaType.Type; } } if (type is null || !typeof(IType).IsAssignableFrom(type)) { throw new SchemaException( SchemaErrorBuilder.New() .SetMessage("The UsePaging attribute needs a valid node schema type.") .SetCode("ATTR_USEPAGING_SCHEMATYPE_INVALID") .Build()); } return(type); }
private void CompleteInterfaces( ICompletionContext context, ObjectTypeDefinition definition) { if (ClrType != typeof(object)) { foreach (Type interfaceType in ClrType.GetInterfaces()) { if (context.TryGetType( new ClrTypeReference(interfaceType, TypeContext.Output), out InterfaceType type)) { _interfaces[type.Name] = type; } } } foreach (ITypeReference interfaceRef in definition.Interfaces) { if (!context.TryGetType(interfaceRef, out InterfaceType type)) { // TODO : resources context.ReportError(SchemaErrorBuilder.New() .SetMessage( "COULD NOT RESOLVE INTERFACE") .SetCode(TypeErrorCodes.MissingType) .SetTypeSystemObject(this) .AddSyntaxNode(SyntaxNode) .Build()); } _interfaces[type.Name] = type; } }
internal sealed override void CompleteName(ICompletionContext context) { if (_definition is null) { throw new InvalidOperationException( TypeResources.TypeSystemObjectBase_DefinitionIsNull); } context.Interceptor.OnBeforeCompleteName( context, _definition, _definition.ContextData); ExecuteConfigurations(context, _definition, ApplyConfigurationOn.Naming); OnCompleteName(context, _definition); if (Name.IsEmpty) { context.ReportError(SchemaErrorBuilder.New() .SetMessage(string.Format( CultureInfo.InvariantCulture, TypeResources.TypeSystemObjectBase_NameIsNull, GetType().FullName)) .SetCode(ErrorCodes.Schema.NoName) .SetTypeSystemObject(this) .Build()); } base.CompleteName(context); context.Interceptor.OnAfterCompleteName( context, _definition, _definition.ContextData); }
private static Schema CompleteSchema( SchemaBuilder builder, IDescriptorContext context, LazySchema lazySchema, TypeRegistry typeRegistry) { SchemaTypesDefinition definition = CreateSchemaDefinition(builder, context, typeRegistry); if (definition.QueryType is null && builder._options.StrictValidation) { throw new SchemaException( SchemaErrorBuilder.New() .SetMessage(TypeResources.SchemaBuilder_NoQueryType) .Build()); } Schema schema = typeRegistry.Types .Select(t => t.Type).OfType <Schema>().First(); schema.CompleteSchema(definition); lazySchema.Schema = schema; context.SchemaInterceptor.OnAfterCreate(context, schema); return(schema); }
private static void AddSerializerToObjectField( ITypeCompletionContext completionContext, ObjectFieldDefinition definition, FieldMiddleware placeholder, NameString typeName) { ITypeInspector typeInspector = completionContext.TypeInspector; IExtendedType? resultType; if (definition.ResultType is not null) { resultType = typeInspector.GetType(definition.ResultType); } else if (definition.Type is ExtendedTypeReference typeReference) { resultType = typeReference.Type; } else { throw new SchemaException(SchemaErrorBuilder.New() .SetMessage("Unable to resolve type from field `{0}`.", definition.Name) .SetTypeSystemObject(completionContext.Type) .Build()); } NameString schemaName = default; completionContext.DescriptorContext.SchemaCompleted += (sender, args) => schemaName = args.Schema.Name; IIdSerializer serializer = completionContext.Services.GetService <IIdSerializer>() ?? new IdSerializer(); var index = definition.MiddlewareComponents.IndexOf(placeholder); definition.MiddlewareComponents[index] = next => async context => { await next(context).ConfigureAwait(false); if (context.Result is not null) { if (resultType.IsArrayOrList) { var list = new List <object?>(); foreach (object?element in (IEnumerable)context.Result) { list.Add(element is null ? element : serializer.Serialize(schemaName, typeName, element)); } context.Result = list; } else { context.Result = serializer.Serialize(schemaName, typeName, context.Result); } } }; }
public static SchemaException FilterConvention_TypeOfMemberIsUnknown(MemberInfo member) => new SchemaException( SchemaErrorBuilder.New() .SetMessage( DataResources.FilterConvention_TypeOfMemberIsUnknown, member.Name, member.DeclaringType?.Name) .Build());
public static SchemaException UsePagingAttribute_NodeTypeUnknown( MemberInfo member) => new SchemaException( SchemaErrorBuilder.New() .SetMessage("The UsePaging attribute needs a valid node schema type.") .SetCode("PAGINATION_SCHEMA_TYPE_INVALID") .SetExtension(nameof(member), member) .Build());