GraphQLMiddleware.cs 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. using GraphQL;
  5. using GraphQL.Http;
  6. using GraphQL.Types;
  7. using Microsoft.AspNetCore.Http;
  8. namespace MySystem.PublicClass.GraphQL
  9. {
  10. public class GraphQLMiddleware : BaseClass
  11. {
  12. private readonly RequestDelegate _next;
  13. private readonly IRepository _repository;
  14. public GraphQLMiddleware(RequestDelegate next, IRepository repository)
  15. {
  16. _next = next;
  17. _repository = repository;
  18. }
  19. public async Task Invoke(HttpContext httpContext)
  20. {
  21. if (httpContext.Request.Path.StartsWithSegments("/g/api"))
  22. {
  23. //string token = httpContext.Request.Headers["token"].ToString();
  24. //string device = httpContext.Request.Headers["device"].ToString();
  25. //bool checkResult = CheckToken(httpContext, device, token);
  26. //if (checkResult)
  27. //{
  28. if (httpContext.Request.Method == "GET")
  29. {
  30. var query = httpContext.Request.Query["query"];
  31. if (!string.IsNullOrWhiteSpace(query))
  32. {
  33. Schema schema = new Schema { Query = new Query(_repository) };
  34. var result = await new DocumentExecuter().ExecuteAsync(options =>
  35. {
  36. options.Schema = schema;
  37. options.Query = query;
  38. });
  39. schema.Dispose();
  40. await WriteResultAsync(httpContext, result);
  41. }
  42. else
  43. {
  44. await _next(httpContext);
  45. }
  46. }
  47. else
  48. {
  49. var stream = new StreamReader(httpContext.Request.Body);
  50. var query = await stream.ReadToEndAsync();
  51. if (!string.IsNullOrWhiteSpace(query))
  52. {
  53. Schema schema = new Schema { Query = new Query(_repository) };
  54. var result = await new DocumentExecuter().ExecuteAsync(options =>
  55. {
  56. options.Schema = schema;
  57. options.Query = query;
  58. });
  59. schema.Dispose();
  60. stream.Dispose();
  61. await WriteResultAsync(httpContext, result);
  62. }
  63. else
  64. {
  65. stream.Dispose();
  66. await _next(httpContext);
  67. }
  68. }
  69. //}
  70. //else
  71. //{
  72. // await _next(httpContext);
  73. //}
  74. }
  75. else
  76. {
  77. await _next(httpContext);
  78. }
  79. }
  80. private async Task WriteResultAsync(HttpContext httpContext, ExecutionResult executionResult)
  81. {
  82. var json = new DocumentWriter(indent:true).Write(executionResult);
  83. httpContext.Response.StatusCode = 200;
  84. httpContext.Response.ContentType = "application/json";
  85. await httpContext.Response.WriteAsync(json);
  86. }
  87. }
  88. }