Skip to content

Easier way to handle batching with the new Graph SDK? #912

@neo773

Description

@neo773

Is there a simple way to do batching with this SDK that I might be missing?

Because right now, this is the solution I landed on — it basically glues together three different libraries:

  • the new SDK (for creating the typesafe request),
  • the old Graph client (for sending the batch request), and
  • the @microsoft/microsoft-graph-types package (to type the output of the batch request).

While this works, it’s not really intuitive. The built-in batching in this SDK returns the body as an ArrayBuffer, so you have to deserialize it — which kind of defeats the whole purpose. Plus, there’s some overhead if you’re dealing with thousands of messages.

I’m just wondering, like I said, is there anything else I can do to make this cleaner or better?

import { MultipartBody } from "@microsoft/kiota-abstractions";
import { authProviderNew, RefreshTokenAuthProvider } from "./auth";
import {
  createGraphServiceClient,
  GraphRequestAdapter,
} from "@microsoft/msgraph-sdk";
import "@microsoft/msgraph-sdk-users";
import { BatchRequestContent } from "@microsoft/msgraph-sdk-core";

import { Client } from "@microsoft/microsoft-graph-client";
import * as MicrosoftGraph from "@microsoft/microsoft-graph-types";

const authProviderKiota = new RefreshTokenAuthProvider();
const adapter = new GraphRequestAdapter(authProviderKiota);
const client = createGraphServiceClient(adapter);

const clientGraph = Client.init({
  defaultVersion: "v1.0",
  debugLogging: false,
  authProvider: authProviderNew,
});

type BatchResponseItem = {
  id: string;
  status: number;
  headers: string[];
  body: MicrosoftGraph.Message;
};

type BatchResponse = { responses: BatchResponseItem[] };

export async function fetchMessagesByBatch(): Promise<
  MicrosoftGraph.Message[]
> {
  const batchLimit = 20;
  const allMessages: MicrosoftGraph.Message[] = [];

  const messageList = await client.me.messages.get({
    queryParameters: {
      select: ["id"],
    },
  });

  const messageIds = messageList?.value ?? [];

  for (let i = 0; i < messageIds.length; i += batchLimit) {
    const batchMessageIds = messageIds.slice(i, i + batchLimit);
    const batchRequestContent = new BatchRequestContent(adapter, {});

    for (const messageId of batchMessageIds) {
      const requestInfo = client.me.messages
        .byMessageId(messageId?.id!)
        .toGetRequestInformation({
          headers: {
            Prefer: 'outlook.body-content-type="text"',
          },
        });

      batchRequestContent.addBatchRequest(requestInfo);
    }

    const batchRequestBody = batchRequestContent.getContent();

    const batchResponse = await clientGraph
      .api("/$batch")
      .post({ requests: batchRequestBody.requests });

    const messages = batchResponse as BatchResponse;
    messages.responses.forEach((v) => allMessages.push(v.body));
  }

  console.dir(allMessages);
  return allMessages;
}

const test = await fetchMessagesByBatch();

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions