Integrating Event Grid with GraphQL (Hot Chocolate) API
Published Feb 03 2022 05:01 AM 2,522 Views
Microsoft

Prerequisites

Why

Adding events to a microservice architecture allows other services in your application ecosystem to engage in complex workflows without losing the value of services being decoupled. You can read more about using events and how they play into a cloud-based architecture here.

Creating the Event Grid Topic

Before we can get started with any code, we should first provision the event grid topic that our events will fall under. You can read how to here. You can also create a bicep file to help with automation of the creation and the event grid topic. Here is the file bicep file where we create the event grid topic and then the API with our endpoint and access key in its appsettings.json file. You can learn more about bicep templates here.

 

 

()
param provisionParameters object
param serverFarmId string
param userAssignedIdentityId string

var teambuilderApiName = 'TeambuilderAPI${uniqueString(resourceGroup().id)}'
var teambuilderPackageUri = contains(provisionParameters, 'teambuilderPackageUri') ? provisionParameters['teambuilderPackageUri'] : 'https://github.com/microsoft/hackathon-team-builder/releases/download/v0.0.15/Teambuilder.API_0.0.15.zip'
var teambuilderEventGridTopicName = 'TeambuilderEventGrid${uniqueString(resourceGroup().id)}'

resource teambuilderEventGridTopic 'Microsoft.EventGrid/topics@2021-12-01' = {
  name: teambuilderEventGridTopicName
  location: resourceGroup().location
  identity: {
    type: 'None'
  }
  properties: {
    inputSchema: 'EventGridSchema'
    publicNetworkAccess: 'Enabled'
    disableLocalAuth: false
  }
}

resource teambuilderApi 'Microsoft.Web/sites@2021-02-01' = {
  kind: 'app'
  name: teambuilderApiName
  location: resourceGroup().location
  properties: {
    serverFarmId: serverFarmId
    keyVaultReferenceIdentity: userAssignedIdentityId    
    httpsOnly: true
    siteConfig: {
      appSettings:  [
        {
          name: 'EventGrid:AccessKey'
          value: teambuilderEventGridTopic.listKeys().key1
        }
        {
          name: 'EventGrid:Endpoint'
          value: teambuilderEventGridTopic.properties.endpoint
        }
      ]
    }
  }
  identity: {
    type: 'UserAssigned'
    userAssignedIdentities: {
      '${userAssignedIdentityId}': {}
    }
  }
}

resource teamBuilderApiDeploy 'Microsoft.Web/sites/extensions@2021-02-01' = {
  parent: teambuilderApi
  name: 'MSDeploy'
  properties: {
    packageUri: teambuilderPackageUri
  }
}

output apiEndpoint string = 'https://${teambuilderApi.properties.defaultHostName}'
output eventGridTopicName string = teambuilderEventGridTopic.name
output webAppResourceId string = teambuilderApi.id

 

 

 

 

This project uses the Teambuilder Toolkit and bicep templates as part of its provisioning process. You can read more about the Teambuilder Toolkit here.

Once your topic is created, we can go ahead and jump into the code. You can find the codebase this blog is written about here.

Message Service

In this post, we are integrating event grid into an existing GraphQL API so we can start by adding the Azure.Messaging.EventGrid NuGet package. In our code, we are using version 4.8.1. Now that we have that package, let us go ahead and create a class that will be our Event Grid messaging service.

Our service will need to use the EventGridPublisherClient from NuGet package we just installed. We can now add a private read-only instantiation of that client that we will create in our constructor. The constructor for that class requires the event grid topic endpoint and an access key. So, let us add those to our constructor’s parameters. We can grab those later with dependency injection.

 

 

 

 

private readonly EventGridPublisherClient _publisherClient;

public EventGridMessageService(IOptions<EventGridMessageServiceConfiguration> config)
{
    Uri.TryCreate(config.Value.Endpoint, UriKind.RelativeOrAbsolute, out var uri);

    var accessKey = new Azure.AzureKeyCredential(config.Value.AccessKey);

    _publisherClient = new EventGridPublisherClient(uri, accessKey);
}

 

 

 

 

Now that we have our client, let us create a simple method to expose sending messages. We can start by just creating a method that just wraps the EventGridPublisherClient’s SendEventAsync method. This method takes in a subject, event type, a data version, and data. The data version will stay constant. The data will be any object that you plan to send, in our case we will be sending the entity that is being mutated. The event type is a string you can use to filter your Event Grid Subscriptions to the event grid topic against. The subject and data can be whatever you want.

 

 

 

 

public async Task SendAsync(string subject, string eventType, string dataVersion, object data)
{
    var message = new EventGridEvent(subject, eventType, dataVersion, data);   

    await _publisherClient.SendEventAsync(message);
}

 

 

 

 

When working with events, it is helpful to have a pattern you want your events to follow so that your subscriptions can know better what to expect. For our pattern, our event type will be a string with the type of the object, we are mutating at the beginning of the string, followed by a period, and followed by the type of mutation. Our subject will describe in plain text what is happening, and our data will be the mutated object.

Since we have this pattern, we can program against it to save ourselves some time using a little string interpolation, an Enum of mutation types, and the typeof operator in dotnet.
We will also make an interface for our service.

Here is our final interface:

 

 

 

 

public interface IMessageService
{
    Task SendAsync<T>(T entity, MutationType mutationType);
}

public enum MutationType
{
    Create,
    Update,
    Delete
}

 

 

 

 

…and our final service class implementing that interface.

 

 

 

 

namespace TeamBuilder.API.Services
{
    public class EventGridMessageService : IMessageService
    {
        private const string DATA_VERSION = "1.0";
        private readonly EventGridPublisherClient _publisherClient;

        public EventGridMessageService(IOptions<EventGridMessageServiceConfiguration> config)
        {
            Uri.TryCreate(config.Value.Endpoint, UriKind.RelativeOrAbsolute, out var uri);

            var accessKey = new Azure.AzureKeyCredential(config.Value.AccessKey);

            _publisherClient = new EventGridPublisherClient(uri, accessKey);
        }

        public async Task SendAsync<T>(T entity, MutationType mutationType)
        {
            var subject = $"{typeof(T).Name} {mutationType.ToString().ToLower()}d";

            var messsage = new EventGridEvent(subject, $"{typeof(T).Name}.{mutationType}", DATA_VERSION, entity);

            await _publisherClient.SendEventAsync(messsage);
        }
    }

    public class EventGridMessageServiceConfiguration
    {
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
        public string Endpoint { get; set; }
        public string AccessKey { get; set; }
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
    }
}

 

 

 

 

(Note that we have created a class for receiving the access key and endpoint that we will require for our constructor.)


Dependency Injection

With our service class and interface written, we can turn our focus on how they will be called and instantiated with dotnet dependency injection. In a standard REST API, we would first add our service to the services in our Startup file and then request it in our controller constructors who need to use that class. With HotChocolate, it is not too different. We will still start by adding our service to services in Startup. We will do this prior to adding our GraphQL server. Be sure to grab your configuration from appsettings.json.

 

 

 

services.Configure<EventGridMessageServiceConfiguration>(Configuration.GetSection("EventGrid"));
services.AddSingleton<IMessageService, EventGridMessageService>();

services
    .AddGraphQLServer()
    .AddQueryType<Query>()

 

 

 

Once our service is available through dependency injection, we can add it to our mutation methods which consume services much the same way that standard REST controllers do. Since our service is a singleton, we will just label it using the service attribute in our method’s constructor.

Using the Message Service

In our mutation method, we now have access to our service and can call the service’s method to send an event after our mutation. Our pattern is the same for all our mutations, complete the mutation and immediately fire off an event under our topic using our method. It is worth noting that for creation, we send the object being created.

 

 

 

[UseTeamBuilderDbContext]
public async Task<AddChallengePayload> AddChallengeAsync(
    AddChallengeInput input,
    [ScopedService] TeamBuilderDbContext context,
    [Service] IMessageService messageService)
{
    var challenge = new ChallengeArea
    {
        Name = input.Name,
        Prefix = input.Prefix,
        Description = input.Description
    };

    context.Challenges.Add(challenge);
    await context.SaveChangesAsync();

    await messageService.SendAsync(challenge, MutationType.Create);

    return new AddChallengePayload(challenge);
}

 

 

 

For updates, we send the updated object.

 

 

 

[UseTeamBuilderDbContext]
public async Task<EditChallengePayload> EditChallengeAsync(
    int id,
    EditChallengeInput input,
    [ScopedService] TeamBuilderDbContext context,
    [Service] IMessageService messageService)
{
    var existingItem = await context.Challenges.FindAsync(id);
    if (existingItem == null)
    {
        return new EditChallengePayload(false, "Item not found.");
    }

    existingItem.Name = string.IsNullOrEmpty(input.Name) ? existingItem.Name : input.Name;
    existingItem.Prefix = string.IsNullOrEmpty(input.Prefix) ? existingItem.Prefix : input.Prefix;
    existingItem.Description = string.IsNullOrEmpty(input.Description) ? existingItem.Description : input.Description;
    context.Entry(existingItem).State = EntityState.Modified;
    await context.SaveChangesAsync();

    await messageService.SendAsync(existingItem, MutationType.Update);

    return new EditChallengePayload(existingItem);
}

 

 

 

And for deletes, we send the object that has been deleted.

 

 

 

[UseTeamBuilderDbContext]
public async Task<DeleteChallengePayload> DeleteChallengeAsync(
        int id,
        [ScopedService] TeamBuilderDbContext context,
        [Service] IMessageService messageService)
{
    var existingItem = await context.Challenges.FindAsync(id);
    if (existingItem == null)
    {
        return new DeleteChallengePayload(false, "Item not found.");
    }
    context.Challenges.Remove(existingItem);
    await context.SaveChangesAsync();

    await messageService.SendAsync(existingItem, MutationType.Delete);

    return new DeleteChallengePayload(true, "Deleted");
}

 

 

 

 

This allows our subscribers to take advantage of the data intelligently. If they need to display information about the recently deleted object, they have the entity in their message since it will no longer be available to them in our data store. Our goal for our messages is to send the most useful information without bloating our message or sending code too much.

Conclusion

Adding events with event grid to your API is simple and fast and a terrific way to add extensibility to your API in Azure. You can read the events posted in several ways. A straightforward way to do so immediately is to just add a storage queue and hook it up to an event subscription and read the queue using Azure Storage Explorer. In part 2, I talk about using an Azure Function to trigger off these events.

Co-Authors
Version history
Last update:
‎May 10 2022 05:03 AM
Updated by: