DotNetBrightener.Integration.GraphQL 1.0.0-beta-007

This is a prerelease version of DotNetBrightener.Integration.GraphQL.
The owner has unlisted this package. This could mean that the package is deprecated, has security vulnerabilities or shouldn't be used anymore.
dotnet add package DotNetBrightener.Integration.GraphQL --version 1.0.0-beta-007
NuGet\Install-Package DotNetBrightener.Integration.GraphQL -Version 1.0.0-beta-007
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DotNetBrightener.Integration.GraphQL" Version="1.0.0-beta-007" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add DotNetBrightener.Integration.GraphQL --version 1.0.0-beta-007
#r "nuget: DotNetBrightener.Integration.GraphQL, 1.0.0-beta-007"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install DotNetBrightener.Integration.GraphQL as a Cake Addin
#addin nuget:?package=DotNetBrightener.Integration.GraphQL&version=1.0.0-beta-007&prerelease

// Install DotNetBrightener.Integration.GraphQL as a Cake Tool
#tool nuget:?package=DotNetBrightener.Integration.GraphQL&version=1.0.0-beta-007&prerelease

GraphQL Integration

DotNetBrightener.Integration.GraphQL is a library that provides APIs to integrate with GraphQL in your Asp.Net Core project with the MVC / Web.API-like style. You will define your GraphQL APIs into controllers / actions and it will just work.

If you are not familar with GraphQL, check out https://github.com/facebook/graphql and https://graphql-dotnet.github.io/docs/getting-started

Feature:

  • WebAPI-like approach of implementing GraphQL
  • Modular, only depends on GraphQL DotNet library

Installation

You can install the library from Nuget Package Management on Visual Studio. Require .Net 5.0. Follow instructions on https://www.nuget.org/packages/DotNetBrightener.Integration.GraphQL for installation options.

Additionally you can download the package and manually reference its dll into your application. You will need to install the dependencies as listed on the Nuget package page

Usage

<a name="configuration-startup"></a>1. Register GraphQL Integration to IServiceCollection

In your Startup.cs's ConfigureService(IServiceCollection services) method, add the following:

// add this using to the using section
using DotNetBrightener.Integration.GraphQL.Extensions;

// ... omitted code

public void ConfigureServices(IServiceCollection services)
{
    // ... omitted codes
    
    // adds GraphQL services
    services.EnableGraphQL();
}

If you have your graph types in the same assembly as Startup class, the above code will automatically register all the types.

Otherwise, assuming you have defined the graph types/queries/mutations (described in Define your models section below) in a separate assembly, then add the reference to that assembly and use the following to register your graph types.

    var assembly = typeof(YourGraphType).Assembly;
    services.AddGraphTypes(assembly);

2. Register GraphQL Integration Middleware

In your Startup.Configure() method, add the following to register the middleware to your application

var graphQLEndpoint = "/[your-desired-endpoint]"; // default is /graphql if you don't specify
var enablePlayground = true; // true to enable UI Playground, false to disable it. Default to true if you don't specify
app.UseGraphQLIntegration(graphQLEndpoint, enablePlayground);

<a name="define-model"></a>3. Define your models (GraphTypes and InputTypes)

ViewModel is a GraphType that exposes your model to the GraphQL queries. InputModel is InputGraphType that receives your input data from client into the GraphQL mutations.

Given you have an entity defined as the following:

public class User 
{
    [Key]
    public long Id { get; set; }
    
    public string UserName { get; set; }
    
    [JsonIgnore] // properties marked with this attribute will not be indexed and returned from the GraphQL API
    public string HashPassword { get; set; }
    
    [NotMapped] // properties marked with this attribute will not be indexed and returned from the GraphQL API
    public string SomeNotMappedProperty { get; set; }
}

You can define ViewModel as the following:

public class UserViewModel: BaseGraphQLViewModel<User> { } // this is minimal set up

All fields defined in your entity class will be defined automatically to the view model, except fields / properties that are marked with the following attributes: [JsonIgnore], [NotMapped], or virtual properties (which we usually use for navigation properties in Entity Framework)

If you want to expose more information into the output of UserViewModel when requested, you can use GraphQLProperty to do this.

public class UserViewModel: BaseGraphQLViewModel<User> 
{ 
    private readonly ISomeService _yourServiceToResolveProperties;
    
    // you can use DependencyInjection here
    public UserViewModel(ISomeService yourService) 
    {
        _yourServiceToResolveProperties = yourService;
    }
    
    // ... omitted code
    
    // retrieve the user groups information from the user view model, if the client side wants to
    [GraphQLProperty("userGroups", typeof(ListGraphType<UserGroupModel>))]
    public IEnumerable<UserGroup> GetUserGroups(IResolveFieldContext<User> context) 
    {
        // IResolveFieldContext<User> context is required to access which user information you are looking at
        var userId = context.Source.Id; // context.Source is the resolved User object, so you can access its data
        
        var userGroups = _yourServiceToResolveProperties.GetGroupsUserBelongsTo(userId);
        
        return userGroups;
    }
} // this is complex set up

You also can define InputModel as following:

public class UserInputModel: BaseGraphQLInputModel<User> { }

To prevent unexpected behaviour, InputModels ignore the fields you mark as Id / Key in the entity class.

For more information about GraphType and InputType, check out the GraphQL documentation.

4. Populate your API as query or mutation

Now that you have ViewModel and InputModel set up, you can wire them up into Queries and Mutations via controller.

Define your query controller as the following

    public class UserQueries : GraphQLController, IGraphQueriesRegistration
    {
        // expose the method as query { users($includeDeleted: BooleanGraphType) { [...fields to pick up] } }
        [GraphQLMethod("users", typeof(ListGraphType<UserViewModel>))]
        public async Task<IEnumerable<User>> GetUsers(bool includeDeleted = false)
        {
            // your logics go here
            
            return users;
        }
    }

Define your mutation controller as the following

    public class UserMutations : GraphQLController, IGraphMutationsRegistration
    {
        // expose the method as mutation { updateUser($userId: longGraphType, $user: UserInputModel) { [...fields to pick up from result] } }
        [GraphQLMethod("updateUser", typeof(UserViewModel))]
        public async Task<User> GetUsers(long userId, User user)
        {
            // your logic to update user goes here
            
            return user;
        }
    }

Controllers which implement IGraphQueriesRegistration and IGraphMutationsRegistration are automatically registered when you use the services.AddGraphTypes(typeof(YourGraphType).Assembly) as described in the Register GraphQL Integration to IServiceCollection section

5. Secure your API

Your APIs (queries and mutations) signatures will be public anyway in the UI Playground if you decide to use it. However, in order to execute a specific query or mutation, if authentication is required, you can add [Authorize] attribute to the method which you want to populate as a query or mutation. User will need to be authenticated in order to perform the query.

In some case, you would like to apply authorization, you can use the ASP.Net MVC approach of authorizing the user to meet certain requirement by using IAuthorizationService.AuthorizeAsync() built-in method, or you can implement one for your project's need.

Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on DotNetBrightener.Integration.GraphQL:

Package Downloads
WebEdFramework

The based library for Modules to be built and run with WebEd CMS or any applications that are based on WebEd Framework

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated

* v1.0.0-beta-007:
- Added support to use [Authorize] on the GraphQLMethod for authorization purpose.