10

So I've been playing around with Hotchocolate lately and I made a class which gives me back a list of students, but I want to have some validation functions for it. I didn't really find anything that helps me from the official hotchocolate website.

Student.cs

public class Student
{
    [GraphQLNonNullType]
    public string Name{ get; set; }
    [GraphQLNonNullType]
    public string LastName{ get; set; }
    [GraphQLNonNullType]
    public string Picture { get; set; }
}

This is my query, which currently gives me back all students from a list.

StudentQuery.cs

public class StudentQuery
{
    [UseFiltering]
    [UseSorting]
    public List<Student> GetStudents()
    {
        return MongoDBHelper.LoadRecords<Student>(EMongoCollection.Students);
    }

}

Now my question is, how can I make a ValidationRule for a student, saying for example that a student has to at least have 3 characters for his name? Could someone be kind enough to provide me some example?

Thanks in advance.

Makus
  • 99
  • 1
  • 8

2 Answers2

15

HotChocolate itself does not have a integration for input validation of this kind. The framework only does GraphQL validation. So checks for invalid GraphQL queries. (e.g. Wrong Type)

If you want to use validation there are a few community libraries to choose from:

Community libraries are listed here: https://github.com/ChilliCream/hotchocolate/blob/main/COMMUNITY.md

Pascal Senn
  • 1,712
  • 11
  • 20
  • Having evaluated the above list for targeting Azure Functions, I found that FluentChoco was very simple to configure and plays nicely with AbstractValidator implementations. It also does not have a dependency on Asp.net (and so can be added to a class library). My only gripe is that it returns validation failures as a 200 via the IGraphQLRequestExecutor (whereas HotChocolate returns 400 for graphQL schema failures). – Marc Stevenson Nov 22 '21 at 02:28
0

Apart from the 3rd party libraries.. we can write a custom middleware to handle the data validation for the data being output from service...

Middleware example code

public class OutputValidationMiddleware
{
    private readonly FieldDelegate next;
    private readonly ILogger<OutputValidationMiddleware> logger;

    public OutputValidationMiddleware(
        FieldDelegate next,
        ILogger<OutputValidationMiddleware> logger)
    {
        this.next = next;
        this.logger = logger;
    }

    public async Task InvokeAsync(IMiddlewareContext context)
    {
        await next(context).ConfigureAwait(false);

        
        if (context.Result != null && context.Result is IValidatable)
        {
            var validationErrors = (context.Result as IValidatable).Validate();
            foreach (var err in validationErrors)
            {
                logger.LogWarning(err);
            }
        }

        return;
    }
}

Now your model needs to implement the IValidatable like below

   public class Test : IValidatable
   {
        IEnumerable<string> Validate()
        {
            // Validate and return any validation errors here.
        }
    }

Now we only need to register it

 services.AddGraphQLServer().
 UseField<OutputValidationMiddleware>()
GPuri
  • 495
  • 4
  • 11