-
Notifications
You must be signed in to change notification settings - Fork 15
Fragments
Stanislav Silin edited this page Apr 17, 2023
·
3 revisions
It is possible to define and reuse fragments:
public static class UserFragments
{
[GraphQLFragment]
public static UserDetails ToUserDetails(this User user)
{
return new UserDetails
{
Id = user.Id,
FirstName = user.FirstName,
LastName = user.LastName
};
}
}
var variables = new { Id = 1 };
var response = await client.Query(
variables,
static (i, q) =>
new
{
Me = q.Me(o => o.ToUserDetails()),
User = q.User(i.Id, o => o.ToUserDetails())
});
Console.WriteLine($"GraphQL: {response.Query}"); // GraphQL: query ($id: Int!) { me { id firstName lastName } user(id: $id) { id firstName lastName } }
Console.WriteLine($"{response.Data.Me.Id}: {response.Data.Me.FirstName} {response.Data.Me.LastName}"); // 1: Jon Smith
Console.WriteLine($"{response.Data.User.Id}: {response.Data.User.FirstName} {response.Data.User.LastName}"); // 1: Jon Smith
The fragment should be marked with the [GraphQLFragment]
attribute, and it should be an extension method. If the fragment is defined in another assembly, it should be a partial method. The last requirement is necessary because source generators don't have access to source code from another assembly. So, a workaround will be to define fragments as a partial method and generate additional metadata.