Use Hot Chocolate and NET 6 to build GraphQL application -- Realizing Mutate to add data

Posted by skot on Sat, 12 Feb 2022 02:36:14 +0100

Python wechat ordering applet course video

https://edu.csdn.net/course/detail/36074

Python actual combat quantitative transaction financial management system

https://edu.csdn.net/course/detail/35475

Series navigation

Use Hot Chocolate and NET 6 to build GraphQL application article index

demand

After discussing the query requirements in GraphQL, in this article, we will demonstrate how to implement the data addition task in GraphQL.

thinking

In GraphQL, query is used to query data, while mutation is used to modify data, including adding and modifying data. The logic of using mutation in Hot Chocolate is basically the same as that of using query, but we need to define the data object for creation or update as needed, so we implement it directly.

realization

To keep things simple, let's first define the following two types:

// Define parameters of new Post
public record AddPostInput(string Title, string Author);

// Define the return object of the new Post
public record AddPostPayload(Post Post);

Create a new station CS is used to define relevant interfaces:

  • Mutation.cs
namespace PostGraphi.Api.GraphQL;

public class Mutation
{
    public async Task<AddPostPayload> AddPostAsync(AddPostInput input, [Service] IRepository<Post> repository)
    {
        return new AddPostPayload(await repository.AddAsync(new Post
        {
            Title = input.Title,
            Author = input.Author
        }));
    }
}


Finally, configure at the place where the service is injected:

  • ProgramExtensions.cs
builder.Services
    .AddGraphQLServer()
    .SetPagingOptions(new PagingOptions
    {
        MaxPageSize = 50,
        IncludeTotalCount = true
    })
    .AddFiltering()
    .AddProjections()
    .AddSorting()
    .AddQueryType<Query>()
    .AddMutationType<Mutation>()
    .AddMutationConventions(new MutationConventionOptions
    {
        ApplyToAllMutations = true,
        InputArgumentName = "input",
        InputTypeNamePattern = "{MutationName}Input",
        PayloadTypeNamePattern = "{MutationName}Payload",
        PayloadErrorTypeNamePattern = "{MutationName}Error",
        PayloadErrorsFieldName = "errors"
    })
    .AddType<PostType>();

This realizes the requirement of adding Post. Let's verify it.

verification

Start the Api project and call the interface:

The log output of the terminal is as follows:

[10:45:15 INF] Executed DbCommand (1ms) [Parameters=[@p0='?' (DbType = Guid), @p1='?', @p2='?' (Size = 13), @p3='?', @p4='?' (DbType = DateTime), @p5='?', @p6='?' (DbType = DateTime), @p7='?', @p8='?', @p9='?' (DbType = DateTime), @p10='?' (Size = 30)], CommandType='Text', CommandTimeout='30']
INSERT INTO "Posts" ("Id", "Abstraction", "Author", "Content", "Created", "CreatedBy", "LastModified", "LastModifiedBy", "Link", "PublishedAt", "Title")
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10);
[10:45:15 INF] Executed endpoint 'Hot Chocolate GraphQL Pipeline'

You can see that the new Post has been stored in the database. We can get the details through the query interface:

summary

In this article, we implemented a simple new Post operation. Here are some contents related to error handling. I didn't demonstrate it in the article. Please refer to the official documents Errors , after customizing the exception object, there are three ways to handle the error: return the exception directly; Using abnormal factory methods; Use constructors. You can even return multiple exceptions at once in AggregateExceptions. The basic idea is realized by adding the attribute [error (typeof (someuserdefinedexception)].

In the next article, we will update the existing data.

Topics: Python .NET computer microsoft graphql