Let's assume that I have the following documents in mongo:
Product:
Product Template:
I mapped product to the following schema:
product {
...
productTemplate {
id,
...
}
...
}
product { productTemplate {id}}
because this information is in the product entity. Is it possible?This is part of my code:
public class ProductType : ObjectType<ProductDocument>
{
protected override void Configure(IObjectTypeDescriptor<ProductDocument> descriptor)
{
descriptor.BindFieldsExplicitly();
descriptor.Name("Product");
descriptor.Field("productTemplate")
.Type<ProductTemplateType>()
.ResolveWith<ProductTemplatesResolver>(r => r.GetProductTemplate(default!, default!, default));
}
}
public class ProductTemplatesResolver
{
public Task<ProductTemplateDocument> GetProductTemplate([Parent] ProductDocument product,
ProductTemplatesBatchDataLoader loader,
CancellationToken cancellationToken)
{
return loader.LoadAsync(product.ProductTemplateId, cancellationToken);
}
}
public class ProductTemplatesBatchDataLoader : BatchDataLoader<int, ProductTemplateDocument>
{
private readonly ProductsDbContext _dbContext;
public ProductTemplatesBatchDataLoader(IBatchScheduler batchScheduler, ProductsDbContext dbContext, DataLoaderOptions? options = null) : base(batchScheduler, options)
{
_dbContext = dbContext;
}
protected override async Task<IReadOnlyDictionary<int, ProductTemplateDocument>> LoadBatchAsync(IReadOnlyList<int> keys, CancellationToken cancellationToken)
{
var pts = await _dbContext.ProductTemplates
.AsQueryable()
.Where(x => keys.Contains(x.Id))
.ToListAsync(cancellationToken);
return pts.ToDictionary(x => x.Id, x => x);
}
}
Thanks
You can get the selected field over IResolverContext GetSelections
public class ProductTemplatesResolver
{
public Task<ProductTemplateDocument> GetProductTemplate(
[Parent] ProductDocument product,
IResolverContext context,
ProductTemplatesBatchDataLoader loader,
CancellationToken cancellationToken)
{
var selectedFields = context.GetSelections((ObjectType)context.Selection.Field.Type);
if (selectedFields.Count == 1 && selectedFields[0].Field.Name == "id")
{
return new ProductDocument(product.TemplateId);
}
return loader.LoadAsync(product.ProductTemplateId, cancellationToken);
}
}