Skip to content

Instantly share code, notes, and snippets.

@dedels
Created October 19, 2017 00:08
Show Gist options
  • Save dedels/c41429e8e14092c459d70519e672d265 to your computer and use it in GitHub Desktop.
Save dedels/c41429e8e14092c459d70519e672d265 to your computer and use it in GitHub Desktop.
using GraphQL;
using GraphQL.Execution;
using GraphQL.Http;
using GraphQL.Types;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace GraphQLConsole
{
public class GraphAppUserContext
{
private TaskCompletionSource<Boolean> batchTaskCompletion = new TaskCompletionSource<Boolean>();
public Task Batch => this.batchTaskCompletion.Task;
public Task Complete()
{
this.batchTaskCompletion.SetResult(true);
return this.batchTaskCompletion.Task;
}
public async Task<T> LazyBatchAsync<T>(Lazy<T> lazy)
{
await this.Batch;
return lazy.Value;
}
}
public class ExecuteBatchListener : DocumentExecutionListenerBase<GraphAppUserContext>
{
public override async Task BeforeExecutionAwaitedAsync(
GraphAppUserContext userContext,
CancellationToken token)
{
await userContext.Complete();
}
}
class Program
{
static void Main(string[] args)
{
Run().Wait();
Console.Write("Enter to continue");
Console.ReadLine();
}
private static async Task Run()
{
var schema = new Schema { Query = new GradeQuery() };
var result = await new DocumentExecuter().ExecuteAsync(_ =>
{
_.Schema = schema;
_.Query = @"
query {
teacher {
id
name
}
}
";
_.UserContext = new GraphAppUserContext();
_.Listeners.Add(new ExecuteBatchListener());
}).ConfigureAwait(false);
var json = new DocumentWriter(indent: true).Write(result);
Console.WriteLine(json);
}
}
public class Teacher
{
public string Id { get; set; }
public string Name { get; set; }
}
public class TeacherType: ObjectGraphType<Teacher>
{
public TeacherType()
{
Field(x => x.Id).Description("Teacher Id");
Field(x => x.Name).Description("Teacher Name");
}
public static Task<Teacher> resolveAsync(ResolveFieldContext<object> arg)
{
//#1: Simplest output
//return new Teacher { Id = "1", Name = "Teacher1" };
//#2: More control on exactly what is returned.
//var lazyTeacher = new Lazy<Teacher>(new Teacher { Id = "1", Name = "Teacher1" });
//await arg.UserContext.As<GraphAppUserContext>().Batch;
//return lazyTeacher.Value;
//#3:less control but also lest code
var lazyTeacher = new Lazy<Teacher>(new Teacher { Id = "1", Name = "Teacher1" });
return arg.UserContext.As<GraphAppUserContext>().LazyBatchAsync(lazyTeacher);
}
}
public class GradeQuery : ObjectGraphType
{
public GradeQuery()
{
Field<TeacherType>("teacher", "Get a teacher profile", resolve: TeacherType.resolveAsync);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment