Tall-Paul / server

ASP.NET Core Server + WebSockets Transport

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

GraphQL for .NET - Subscription Transport WebSockets

Build status

Activity Activity Activity

Size

Provides the following packages:

Package Downloads Nuget Latest MyGet Latest
GraphQL.Server.Core Nuget Nuget MyGet
GraphQL.Server.Transports.AspNetCore Nuget Nuget MyGet
GraphQL.Server.Transports.AspNetCore.NewtonsoftJson Nuget Nuget MyGet
GraphQL.Server.Transports.AspNetCore.SystemTextJson Nuget Nuget MyGet
GraphQL.Server.Transports.Subscriptions.Abstractions Nuget Nuget MyGet
GraphQL.Server.Transports.WebSockets Nuget Nuget MyGet
GraphQL.Server.Ui.Altair Nuget Nuget MyGet
GraphQL.Server.Ui.Playground Nuget Nuget MyGet
GraphQL.Server.Ui.GraphiQL Nuget Nuget MyGet
GraphQL.Server.Ui.Voyager Nuget Nuget MyGet
GraphQL.Server.Authorization.AspNetCore Nuget Nuget MyGet

Transport compatible with Apollo subscription protocol.

Getting started

WARNING: The latest stable version 3.4.0 has many known issues that have been fixed in 3.5.0-alphaXXXX versions. If errors occur, it is recommended that you first check the behavior on the latest available alpha version before reporting a issue. Latest 3.5.0-alphaXXXX versions are backwards incompatible with the latest stable 2.4.0 version of GraphQL.NET. You can see the changes in public APIs using fuget.org.

You can install the latest stable version via NuGet.

> dotnet add package GraphQL.Server.Transports.AspNetCore

You can get the latest pre-release packages from the MyGet feed, where you may want to explicitly pull a certain version using -v.

> dotnet add package GraphQL.Server.Transports.AspNetCore -v 3.5.0-alpha0068

For just the HTTP middleware:

dotnet add package GraphQL.Server.Transports.AspNetCore

The HTTP middleware needs an IGraphQLRequestDeserializer implementation:

.NET Core 3+:
dotnet add package GraphQL.Server.Transports.AspNetCore.SystemTextJson
Legacy (prior to .NET Core 3):
dotnet add package GraphQL.Server.Transports.AspNetCore.NewtonsoftJson
(or your own)

For more information on how to migrate from Newtonsoft.Json to System.Text.Json see this article.

For the WebSocket subscription protocol (depends on above) middleware:

dotnet add package GraphQL.Server.Transports.WebSockets

For the UI middleware/s:

dotnet add package GraphQL.Server.Ui.Altair
dotnet add package GraphQL.Server.Ui.GraphiQL
dotnet add package GraphQL.Server.Ui.Playground
dotnet add package GraphQL.Server.Ui.Voyager

Configure

See the sample project's Startup.cs for full details.

public void ConfigureServices(IServiceCollection services)
{
    // Add GraphQL services and configure options
    services
        .AddSingleton<IChat, Chat>()
        .AddSingleton<ChatSchema>()
        .AddGraphQL((options, provider) =>
        {
            options.EnableMetrics = Environment.IsDevelopment();
            options.ExposeExceptions = Environment.IsDevelopment();
            var logger = provider.GetRequiredService<ILogger<Startup>>();
            options.UnhandledExceptionDelegate = ctx => logger.LogError("{Error} occured", ctx.OriginalException.Message);
        })
        // Add required services for de/serialization
        .AddSystemTextJson(deserializerSettings => { }, serializerSettings => { }) // For .NET Core 3+
        .AddNewtonsoftJson(deserializerSettings => { }, serializerSettings => { }) // For everything else
        .AddWebSockets() // Add required services for web socket support
        .AddDataLoader() // Add required services for DataLoader support
        .AddGraphTypes(typeof(ChatSchema)) // Add all IGraphType implementors in assembly which ChatSchema exists 
}

public void Configure(IApplicationBuilder app)
{
    // this is required for websockets support
    app.UseWebSockets();

    // use websocket middleware for ChatSchema at path /graphql
    app.UseGraphQLWebSockets<ChatSchema>("/graphql");

    // use HTTP middleware for ChatSchema at path /graphql
    app.UseGraphQL<ChatSchema>("/graphql");

    // use graphiQL middleware at default url /ui/graphiql
    app.UseGraphiQLServer(new GraphiQLOptions());

    // use graphql-playground middleware at default url /ui/playground
    app.UseGraphQLPlayground(new GraphQLPlaygroundOptions());

    // use altair middleware at default url /ui/altair
    app.UseGraphQLAltair(new GraphQLAltairOptions());
    
    // use voyager middleware at default url /ui/voyager
    app.UseGraphQLVoyager(new GraphQLVoyagerOptions());
}

UserContext and resolvers

UserContext of your resolver will be type of MessageHandlingContext. You can access the properties including your actual UserContext by using the Get<YourContextType>("UserContext") method. This will read the context from the properties of MessageHandlingContext. You can add any other properties as to the context in IOperationMessageListeners. See the sample for example of injecting ClaimsPrincipal.

Sample

Samples.Server shows a simple Chat example demonstrating the subscription transport. It can be run as netcoreapp2.2, netcoreapp3.0 or netcoreapp3.1, and supports various GraphQL client IDEs (by default opening GraphQL Playground).

Here are some example queries to get started. Use three browser tabs or better yet windows to view the changes.

Subscription 1

Query:

subscription MessageAddedByUser($id:String!) {
  messageAddedByUser(id: $id) {
    from { id displayName }
    content
  }
}

Variables:

{
  "id": "1"
}

Subscription 2

subscription MessageAdded {
  messageAdded {
    from { id displayName }
    content
  }
}

Mutation

Query:

mutation AddMessage($message: MessageInputType!) {
  addMessage(message: $message) {
    from {
      id
      displayName
    }
    content
  }
}

Variables:

{
  "message": {
    "content": "Message",
    "fromId": "1"
  }
}

About

ASP.NET Core Server + WebSockets Transport

License:MIT License


Languages

Language:C# 90.9%Language:HTML 4.5%Language:PowerShell 3.3%Language:Shell 1.2%