In case you didn’t notice, I’m a big fan of GraphQL. Most of the time I use GraphQL.NET and more specifically the GraphType first approach; https://graphql-dotnet.github.io/docs/getting-started/introduction#graphtype-first-approach.
The disadvantage of this approach is that you don’t have a schema file but that the schema is generated dynamically from your mappings.
Why is this a problem?
There are a number of tools that expect to work from a schema file and try to import it.
Luckily it is not that hard to create some extra middleware that allows us to export the schema from a GraphQL.NET service:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SchemaMiddleware | |
{ | |
private readonly RequestDelegate _next; | |
public SchemaMiddleware(RequestDelegate next) | |
{ | |
_next = next; | |
} | |
public async Task Invoke(HttpContext context, OrdersSchema schema) | |
{ | |
using (var printer = new SchemaPrinter(schema)) | |
{ | |
context.Response.ContentType = "application/text"; | |
context.Response.StatusCode = (int)HttpStatusCode.OK; | |
await context.Response.WriteAsync(printer.Print()); | |
return; | |
} | |
} | |
} |
To invoke this middleware we add it inside our Startup configuration:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void Configure(IApplicationBuilder app, IHostingEnvironment env) | |
{ | |
if (env.IsDevelopment()) | |
{ | |
app.UseDeveloperExceptionPage(); | |
} | |
app.UseDefaultFiles(); | |
app.UseStaticFiles(); | |
app.UseWebSockets(); | |
app.UseGraphQLWebSocket<OrdersSchema>(new GraphQLWebSocketsOptions()); | |
app.UseGraphQLHttp<OrdersSchema>(new GraphQLHttpOptions()); | |
app.Map("/schema.graphql", config => config.UseMiddleware<SchemaMiddleware>()); | |
} |