|
| 1 | +using GraphQL.Server.Ui.Altair.Internal; |
| 2 | +using Microsoft.AspNetCore.Http; |
| 3 | +using System; |
| 4 | +using System.Text; |
| 5 | +using System.Threading.Tasks; |
| 6 | + |
| 7 | +namespace GraphQL.Server.Ui.Altair |
| 8 | +{ |
| 9 | + /// <summary> |
| 10 | + /// A middleware for Altair GraphQL |
| 11 | + /// </summary> |
| 12 | + public class AltairMiddleware |
| 13 | + { |
| 14 | + private readonly GraphQLAltairOptions _options; |
| 15 | + |
| 16 | + /// <summary> |
| 17 | + /// The next middleware |
| 18 | + /// </summary> |
| 19 | + private readonly RequestDelegate _nextMiddleware; |
| 20 | + |
| 21 | + /// <summary> |
| 22 | + /// The page model used to render Altair |
| 23 | + /// </summary> |
| 24 | + private AltairPageModel _pageModel; |
| 25 | + |
| 26 | + /// <summary> |
| 27 | + /// Create a new <see cref="AltairMiddleware"/> |
| 28 | + /// </summary> |
| 29 | + /// <param name="nextMiddleware">The next middleware</param> |
| 30 | + /// <param name="options">Options to customize middleware</param> |
| 31 | + public AltairMiddleware(RequestDelegate nextMiddleware, GraphQLAltairOptions options) |
| 32 | + { |
| 33 | + _nextMiddleware = nextMiddleware ?? throw new ArgumentNullException(nameof(nextMiddleware)); |
| 34 | + _options = options ?? throw new ArgumentNullException(nameof(options)); |
| 35 | + } |
| 36 | + |
| 37 | + /// <summary> |
| 38 | + /// Try to execute the logic of the middleware |
| 39 | + /// </summary> |
| 40 | + /// <param name="httpContext">The HttpContext</param> |
| 41 | + public Task Invoke(HttpContext httpContext) |
| 42 | + { |
| 43 | + if (httpContext == null) throw new ArgumentNullException(nameof(httpContext)); |
| 44 | + |
| 45 | + return IsAltairRequest(httpContext.Request) |
| 46 | + ? InvokeAltair(httpContext.Response) |
| 47 | + : _nextMiddleware(httpContext); |
| 48 | + } |
| 49 | + |
| 50 | + private bool IsAltairRequest(HttpRequest httpRequest) |
| 51 | + { |
| 52 | + return HttpMethods.IsGet(httpRequest.Method) && httpRequest.Path.StartsWithSegments(_options.Path); |
| 53 | + } |
| 54 | + |
| 55 | + private Task InvokeAltair(HttpResponse httpResponse) |
| 56 | + { |
| 57 | + httpResponse.ContentType = "text/html"; |
| 58 | + httpResponse.StatusCode = 200; |
| 59 | + |
| 60 | + // Initialize page model if null |
| 61 | + if (_pageModel == null) |
| 62 | + _pageModel = new AltairPageModel(_options); |
| 63 | + |
| 64 | + var data = Encoding.UTF8.GetBytes(_pageModel.Render()); |
| 65 | + return httpResponse.Body.WriteAsync(data, 0, data.Length); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments