hotchoc graphql with database services

To setup graphql backend that lookup database records, you can use  hotchoc's ServiceAttribute, as shown in the code snippet here:

using System.Collections.Generic;
using HotChocolate;
using HotChocolate.Types;
using HotChocolate.Types.Relay;

namespace Accounts.Types
{
    [QueryType]
    public class Query
    {        
        public IEnumerable<User> GetUsers([Service] UserRepository repository) =>
            repository.GetUsers();

        [NodeResolver]
        public User GetUser(int id, [Service] UserRepository repository) =>
            repository.GetUser(id);
    }
}


You can add database customization code later, for a demo example, a UserRepository would look like this. 


public class UserRepository
    {
        private readonly Dictionary<int, User> _users;

        public UserRepository()
        {
            _users = new User[]
            {
                new User(1, "Ada Lovelace", new DateTime(1815, 12, 10), "@ada"),
                new User(2, "Alan Turing", new DateTime(1912, 06, 23), "@complete")
            }.ToDictionary(t => t.Id);
        }

        public User GetUser(int id) => _users[id];

        public IEnumerable<User> GetUsers() => _users.Values;
    }

To wire it all up, you can do the following in Program.cs.

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Accounts.Types;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddSingleton<UserRepository>();

builder.Services
    .AddGraphQLServer()
    .AddTypes()
    .AddGlobalObjectIdentification()
    .RegisterService<UserRepository>();

var app = builder.Build();
app.MapGraphQL();
app.RunWithGraphQLCommands(args);

For a complete code example, please check out

https://github.com/mitzenjeremywoo/hotchoc-federation-centralize.git





Comments

Popular posts from this blog

gemini cli getting file not defined error

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20

vllm : Failed to infer device type