Response Pruner

Last updated: June 13th, 2020

Response Pruner

Registering

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();
    services.AddPartialResponse();
}

Usage

If your endpoint's response structure is
{
    "id": 1,
    "name": "John",
    "age": 65,
    "friends": [
        {
            "id": 2,
            "name": "Tim",
            "age": 23
        }
    ]
}
Given a query string of
?fields=id,friends{id,name}
Would result with a response of
{
    "id": 1,
    "friends": [
        {
            "id": 2,
            "name": "Tim"
        }
    ]
}

Internally Response Pruner uses Fields Queries library to parse the query string

Customization

services.AddResponsePruner(options =>
{
    // By default, JsonPruner implementation is used, but
    // if you API wraps the responses, you can override the default
    // with WrapperAwareJsonPruner and prividing the field name which needs
    // to be unwrapped. Ex: For { page: 1, data: [ { name: "item" } ] }
    // root wrapper will be ignored and we'll start prunning from [ { name: "item" } ]
    options.Pruner = c => new WrapperAwareJsonPruner("data");

    // You can configure a custom IRequestFieldsTokensProvider implementation,
    // which is responsible for providing requested fields
    // By default, we'll search for `?fields=` query string in current request.
    options.RequestFieldsTokensProvider = c => new YourImplementation();
});