-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFileUploadTests.cs
More file actions
150 lines (136 loc) · 6.44 KB
/
Copy pathFileUploadTests.cs
File metadata and controls
150 lines (136 loc) · 6.44 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
using GraphQLParser.AST;
using Microsoft.Extensions.Hosting;
#if NET48 || NETCOREAPP2_1
using IHostApplicationLifetime = Microsoft.Extensions.Hosting.IApplicationLifetime;
#endif
namespace Tests.Middleware;
public class FileUploadTests : IDisposable
{
private readonly TestServer _server;
public FileUploadTests()
{
var hostBuilder = new WebHostBuilder();
hostBuilder.ConfigureServices(services => {
services.AddSingleton<FileGraphType>();
services.AddGraphQL(b => b
.AddSchema<MySchema>()
.AddSystemTextJson());
});
hostBuilder.Configure(app => {
app.UseWebSockets();
app.UseGraphQL<MyMiddleware>("/graphql", new GraphQLHttpMiddlewareOptions());
});
_server = new TestServer(hostBuilder);
_server.Host.Services.GetRequiredService<ISchema>().Initialize();
}
public void Dispose() => _server.Dispose();
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task Basic(bool withOtherVariables)
{
var client = _server.CreateClient();
var content = new MultipartFormDataContent();
var queryContent = new StringContent(@"query($prefix: String, $file: File!) { convertToBase64(prefix: $prefix, file: $file) }");
queryContent.Headers.ContentType = new("application/graphql");
content.Add(queryContent, "query");
if (withOtherVariables) {
var variablesContent = new StringContent(@"{""prefix"":""pre-""}");
variablesContent.Headers.ContentType = new("application/json");
content.Add(variablesContent, "variables");
}
var fileData = Encoding.UTF8.GetBytes("abcd");
var fileContent = new ByteArrayContent(fileData);
fileContent.Headers.ContentType = new("application/octet-stream");
content.Add(fileContent, "file", "filename.bin");
using var request = new HttpRequestMessage(HttpMethod.Post, "/graphql");
request.Content = content;
request.Headers.Add("GraphQL-Require-Preflight", "true");
using var response = await client.SendAsync(request);
if (withOtherVariables) {
await response.ShouldBeAsync(@"{""data"":{""convertToBase64"":""pre-filename.bin-YWJjZA==""}}");
} else {
await response.ShouldBeAsync(@"{""data"":{""convertToBase64"":""filename.bin-YWJjZA==""}}");
}
}
public class MyMiddleware : GraphQLHttpMiddleware<MySchema>
{
private readonly IGraphQLTextSerializer _serializer;
#pragma warning disable CS0618 // Type or member is obsolete
public MyMiddleware(RequestDelegate next, IGraphQLTextSerializer serializer, IDocumentExecuter<MySchema> documentExecuter, IServiceScopeFactory serviceScopeFactory, GraphQLHttpMiddlewareOptions options, IHostApplicationLifetime hostApplicationLifetime)
#pragma warning restore CS0618 // Type or member is obsolete
: base(next, serializer, documentExecuter, serviceScopeFactory, options, hostApplicationLifetime)
{
_serializer = serializer;
}
protected override async Task<(GraphQLRequest? SingleRequest, IList<GraphQLRequest?>? BatchRequest)?> ReadPostContentAsync(
HttpContext context, RequestDelegate next, string? mediaType, Encoding? sourceEncoding)
{
if (context.Request.HasFormContentType) {
try {
var formCollection = await context.Request.ReadFormAsync(context.RequestAborted);
return (DeserializeFromFormBody(formCollection), null);
} catch (Exception ex) {
if (!await HandleDeserializationErrorAsync(context, next, ex))
throw;
return null;
}
}
return await base.ReadPostContentAsync(context, next, mediaType, sourceEncoding);
}
private GraphQLRequest DeserializeFromFormBody(IFormCollection formCollection)
{
var request = new GraphQLRequest {
Query = formCollection.TryGetValue("query", out var queryValues) ? queryValues[0] : null,
Variables = formCollection.TryGetValue("variables", out var variablesValues) ? _serializer.Deserialize<Inputs>(variablesValues[0]) : null,
Extensions = formCollection.TryGetValue("extensions", out var extensionsValues) ? _serializer.Deserialize<Inputs>(extensionsValues[0]) : null,
OperationName = formCollection.TryGetValue("operationName", out var operationNameValues) ? operationNameValues[0] : null,
};
if (formCollection.Files.Count > 0) {
var dic = request.Variables != null ? new Dictionary<string, object?>(request.Variables) : new Dictionary<string, object?>();
foreach (var file in formCollection.Files) {
dic.Add(file.Name, file);
}
request.Variables = new Inputs(dic);
}
return request;
}
}
public class MySchema : Schema
{
public MySchema()
{
var query = new ObjectGraphType {
Name = "Query",
};
query.Field<StringGraphType>("ConvertToBase64")
.Argument<StringGraphType>("prefix")
.Argument<NonNullGraphType<FileGraphType>>("file")
.Resolve(context => {
var prefix = context.GetArgument<string?>("prefix");
var file = context.GetArgument<IFormFile>("file");
var memStream = new MemoryStream();
file.CopyTo(memStream);
var bytes = memStream.ToArray();
return prefix + file.FileName + "-" + Convert.ToBase64String(bytes);
});
Query = query;
}
}
public class FileGraphType : ScalarGraphType
{
public FileGraphType()
{
Name = "File";
}
public override object? ParseLiteral(GraphQLValue value)
=> value is GraphQLNullValue ? null : ThrowLiteralConversionError(value);
public override object? ParseValue(object? value) => value switch {
null => null,
IFormFile => value,
_ => ThrowValueConversionError(value),
};
public override object? Serialize(object? value)
=> throw new InvalidOperationException("This scalar does not support serialization.");
}
}