Skip to content

Instantly share code, notes, and snippets.

@benmccallum
Created July 27, 2022 23:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benmccallum/57d7687cd38d4a6504ad9f09c325fece to your computer and use it in GitHub Desktop.
Save benmccallum/57d7687cd38d4a6504ad9f09c325fece to your computer and use it in GitHub Desktop.
Removing fields with ITypeRewriter
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