Created
July 27, 2022 23:52
-
-
Save benmccallum/57d7687cd38d4a6504ad9f09c325fece to your computer and use it in GitHub Desktop.
Removing fields with ITypeRewriter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using HotChocolate.Language; | |
using HotChocolate.Stitching.Merge; | |
using HotChocolate.Stitching.Merge.Rewriters; | |
using HotChocolate.Types; | |
namespace MyCompany.GraphQLService.Stitching | |
{ | |
internal class RemoveFieldsRewriter : ITypeRewriter | |
{ | |
public ITypeDefinitionNode Rewrite(ISchemaInfo schema, ITypeDefinitionNode typeDefinition) | |
{ | |
if (schema.Name.HasValue && | |
typeDefinition is ObjectTypeDefinitionNode otd) | |
{ | |
return RemoveFields(schema.Name, otd, _shouldKeepCheck, f => otd.WithFields(f)); | |
} | |
return typeDefinition; | |
} | |
private static readonly Func<string, FieldDefinitionNode, bool> _shouldKeepCheck = (schemaName, field) => | |
_someListOfFieldsYouWantToKeepMaybeLoadedFromExternalFile.Contains(field.Name.Value); | |
private static T RemoveFields<T>( | |
string schemaName, | |
T typeDefinition, | |
Func<string, FieldDefinitionNode, bool> shouldKeep, | |
RewriteFieldsDelegate<T> rewrite) | |
where T : ComplexTypeDefinitionNodeBase, ITypeDefinitionNode | |
{ | |
var keptFields = new List<FieldDefinitionNode>(); | |
foreach (var field in typeDefinition.Fields) | |
{ | |
if (shouldKeep(schemaName, field)) | |
{ | |
keptFields.Add(field); | |
} | |
} | |
return rewrite(keptFields); | |
} | |
internal delegate T RewriteFieldsDelegate<T>( | |
IReadOnlyList<FieldDefinitionNode> fields) | |
where T : ComplexTypeDefinitionNodeBase, ITypeDefinitionNode; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment