Skip to content

Batch pattern in 1.19.0-preview.1 suggested changes to help with referencing responses #51

@jthake

Description

@jthake

In looking at the new Batch approach in 1.19.0-preview.1 .

// Add batch request steps to BatchRequestContent.
BatchRequestContent batchRequestContent = new BatchRequestContent(batchRequestStep1, batchRequestStep2);

/* Use the Request builders :) */
BatchResponseContent returnedResponse = await graphServiceClient.Batch.Request().PostAsync(batchRequestContent);

/* Read the responses :) */
HttpResponseMessage firstResponse = await returnedResponse.GetResponseByIdAsync("1");
            HttpResponseMessage secondResponse = await returnedResponse.GetResponseByIdAsync("2");

It was not intuitive to have to create your own id's to fetch the response from the dictionary. In this example they actually came back null.

So we'd like to propose this change:

IUserRequest userRequest = graphClient.Me.Request();
IUserEventsCollectionRequest eventsRequest = graphClient.Me.Events.Request();

BatchRequestContent batchRequestContent = new BatchRequestContent();
var userRequestId = batchRequestContent.AddBatchRequestStepWithId(userRequest);
var eventsRequestId = batchRequestContent.AddBatchRequestStepWithId(eventsRequest);

BatchResponseContent returnedResponse = await graphClient.Batch.Request().PostAsync(batchRequestContent);
User user = await returnedResponse.GetResponseByIdAsync<User>(userRequestId);
UserEventsCollectionResponse events = await returnedResponse.GetResponseByIdAsync<UserEventsCollectionResponse>(eventsRequestId);

@darrelmiller and I wrote these extension methods to clean it up. Is it possible to add this directly into the SDK?

    public static class BatchExtensions { 

        public async static Task<T> GetResponseByIdAsync<T>(this BatchResponseContent returnedResponse, string id)
        {
            var responseHandler = new ResponseHandler(new Serializer());
            HttpResponseMessage response = await returnedResponse.GetResponseByIdAsync(id);
            return await responseHandler.HandleResponse<T>(response);
        }

        public static string AddBatchRequestStepWithId(this BatchRequestContent batchRequestContent, IBaseRequest request)
        {
            var id = Guid.NewGuid().ToString();
            batchRequestContent.AddBatchRequestStep(new BatchRequestStep(id, request.GetHttpRequestMessage()));
            return id;
        }
  }

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions