Skip to content
Charles Solar edited this page Jun 15, 2018 · 1 revision

Querying is handled via NServiceBus's request/response feature. In the catalog context - we define a service to retrieve all products like so:

[Api("Catalog")]
[Route("/catalog", "GET")]
public class Catalog : Paged<Models.CatalogProductIndex>
{
    public Guid? BrandId { get; set; }
    public Guid? TypeId { get; set; }
    public string Search { get; set; }
}

public Task<object> Any(Services.Catalog request)
{
    return _bus.RequestPaged<Queries.Catalog, Models.CatalogProductIndex>(new Queries.Catalog
    {
        BrandId = request.BrandId,
        TypeId = request.TypeId,
        Search = request.Search
    });
}

What this does is send a request of type Queries.Catalog out the bus to the elastic endpoint. In this app all requests for paged data (lists of data typically represented as a grid or containing searching/paging) are routed to elastic. Elastic handles this request:

public class Handler :
    IHandleQueries<Queries.Catalog>
{
    public async Task Handle(Queries.Catalog query, IMessageHandlerContext ctx)
    {
        var builder = new QueryBuilder();
        if (query.BrandId.HasValue)
            builder.Add("CatalogBrandId", query.BrandId.ToString(), Operation.EQUAL);
        if (query.TypeId.HasValue)
            builder.Add("CatalogTypeId", query.TypeId.ToString(), Operation.EQUAL);

        if (!string.IsNullOrEmpty(query.Search))
            builder.Grouped(Group.ANY)
                .Add("Name", query.Search, Operation.CONTAINS)
                .Add("Description", query.Search, Operation.CONTAINS);

        var results = await ctx.App<Infrastructure.IUnitOfWork>().Query<Models.CatalogProductIndex>(builder.Build())
            .ConfigureAwait(false);

        await ctx.Result(results.Records, results.Total, results.ElapsedMs).ConfigureAwait(false);
    }
}

As you can see most of the actual query work is done by the endpoint UOW instance - which is not that interesting for this purpose.

Using ctx.Result will return the data we received from elastic db back to the requesting endpoint (servicestack).

Clone this wiki locally