-
Notifications
You must be signed in to change notification settings - Fork 27
/
GraphiQlExtensions.cs
76 lines (61 loc) · 2.51 KB
/
GraphiQlExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;
namespace GraphiQl
{
public static class GraphiQlExtensions
{
private const string DefaultPath = "/graphql";
public static IApplicationBuilder UseGraphiQl(this IApplicationBuilder app)
=> UseGraphiQl(app, DefaultPath);
public static IApplicationBuilder UseGraphiQl(this IApplicationBuilder app, string path)
=> UseGraphiQlIml(app, path);
private static IApplicationBuilder UseGraphiQlIml(this IApplicationBuilder app, string path)
{
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentException(nameof(path));
var p = path.EndsWith("/") ? path : $"{path}/" + "graphql-path.js";
app.Map(p, x => WritePathJavaScript(x, path));
return UseGraphiQlImp(app, x => x.SetPath(path));
}
private static IApplicationBuilder UseGraphiQlImp(this IApplicationBuilder app,
Action<GraphiQlConfig> setConfig)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
if (setConfig == null)
throw new ArgumentNullException(nameof(setConfig));
var config = new GraphiQlConfig();
setConfig(config);
var fileServerOptions = new FileServerOptions
{
RequestPath = config.Path,
FileProvider = BuildFileProvider(),
EnableDefaultFiles = true,
StaticFileOptions = {ContentTypeProvider = new FileExtensionContentTypeProvider()}
};
app.UseFileServer(fileServerOptions);
return app;
}
private static IFileProvider BuildFileProvider()
{
var assembly = typeof(GraphiQlExtensions).GetTypeInfo().Assembly;
var embeddedFileProvider = new EmbeddedFileProvider(assembly, "graphiql.assets");
var fileProvider = new CompositeFileProvider(
embeddedFileProvider
);
return fileProvider;
}
private static void WritePathJavaScript(IApplicationBuilder app, string path)
{
app.Run(h =>
{
h.Response.ContentType = "application/javascript";
return h.Response.WriteAsync($"var graphqlPath='{path}';");
});
}
}
}