-
Notifications
You must be signed in to change notification settings - Fork 48
/
Connection.cs
72 lines (62 loc) · 2.38 KB
/
Connection.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
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Octokit.GraphQL.Internal;
namespace Octokit.GraphQL
{
/// <inheritdoc />
public class Connection : IConnection
{
/// <summary>
/// The address of the GitHub GraphQL API.
/// </summary>
public static readonly Uri GithubApiUri = new Uri("https://api.github.com/graphql");
/// <inheritdoc />
public Connection(ProductHeaderValue productInformation, string token)
: this(productInformation, GithubApiUri, token)
{
}
/// <inheritdoc />
public Connection(ProductHeaderValue productInformation, Uri uri, string token)
: this(productInformation, uri, new InMemoryCredentialStore(token))
{
}
/// <inheritdoc />
public Connection(ProductHeaderValue productInformation, ICredentialStore credentialStore)
: this(productInformation, GithubApiUri, credentialStore)
{
}
/// <inheritdoc />
public Connection(ProductHeaderValue productInformation, Uri uri, ICredentialStore credentialStore)
{
Uri = uri;
CredentialStore = credentialStore;
HttpClient = CreateHttpClient(productInformation);
}
public Uri Uri { get; }
protected ICredentialStore CredentialStore { get; }
protected HttpClient HttpClient { get; }
public async Task<string> Run(string query)
{
var token = await CredentialStore.GetCredentials();
using (var request = new HttpRequestMessage(HttpMethod.Post, Uri))
{
request.Content = new StringContent(query);
request.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
using (var response = await HttpClient.SendAsync(request))
{
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
}
private HttpClient CreateHttpClient(ProductHeaderValue header)
{
var result = new HttpClient();
var userAgent = new ProductInfoHeaderValue(header.Name, header.Version);
result.DefaultRequestHeaders.UserAgent.Add(userAgent);
return result;
}
}
}