To obtain information about the user and the respective photo, we have to make two requests, one to obtain user information and the other to obtain a photo. If your application obtains information from just one user, this may not be a problem, but if you need to obtain a list of users, there will be a performance degradation, since for each user we have to make two requests.
For example to create a list of contacts like the below, even with paging (20 items) we will have to wait some seconds to show the list.
To limit the number of requests we can use MS Graph Batch, this allows us to combine several requests in one HTTP call, all requests are executed on the server and when all requests are made we receive the result of each request. Each request is defined in the JSON object array that is passed as a property to the MS Graph Batch API.
Here my snippet to get information of user and photo and save the information on local cache:
/**
* Get User Data
* @param user
*/
const getUserId = async (user: string): Promise<IUserInfo> => {
let userInfo: IUserInfo;
let blobPhoto: string;
let usersResults: User;
// Create a Batch Request
// 2 rquests
// id=1 = user Info
// id=2 = user Photo
const batchRequests: IBatchRequest[] = [
{
id: "1",
url: `/users/${user}`,
method: "GET",
headers: {
ConsistencyLevel: "eventual",
},
},
{
id: "2",
url: `/users/${user}/photo/$value`,
headers: { "content-type": "img/jpg" },
method: "GET",
},
];
// Try to get user information from cache
try {
userInfo = await cache.get(`${user}`);
return userInfo;
} catch (error) {
// execute batch
const batchResults: any = await msgGraphclient
.api(`/$batch`)
.version("v1.0")
.post({ requests: batchRequests });
// get Responses
const responses: any = batchResults.responses;
// load responses
for (const response of responses) {
// user info
switch (response.id) {
case "1":
usersResults = response.body;
break;
case "2":
const binToBlob = response?.body
? await b64toBlob(response?.body, "img/jpg")
: undefined;
blobPhoto = (await blobToBase64(binToBlob)) ?? undefined;
break;
default:
break;
}
}
// save userinfo in cache
userInfo = { ...usersResults, userPhoto: blobPhoto };
// return Userinfo with photo
await cache.put(`${user}`, userInfo);
return userInfo;
}
};
With this code we get all the information of the user and photo in a single request and minimize the application network latency and with cache we only do a request if user not exists, and return an object
Please see all code here
Thank you for reading !