I would like to be able to retrieve all users in my Azure Active Directory and cache it so I could filter my users on demande. I know about the nextLink used for Pagination. I’m fairly new in the React world and Javascript so I need some help understanding how to cycle through all pages to get all my users. Here’s the code I have right now :
export async function searchADUser(searchQuery?: string, filter: string, orderBy: string = 'displayName')
{
const searchedUser = await graphClient!
.api('/users')
.header('ConsistencyLevel', 'eventual')
.filter(`${filter}`)
.search(`"${searchQuery}"`)
.orderby(`${orderBy}`)
.get();
const nextLink = searchedUser["@odata.nextLink"]
return searchedUser;
I was able to access the nextLink url using the [“@odata.nextLink”]. So my question is how to get all users ? Do I just loop until nextLink is null or there is a better way.
Thank you
Advertisement
Answer
Here’s the code to be able to get all pages of data from a Microsoft Graph :
export async function getAllAADUsers(
authProvider: AuthCodeMSALBrowserAuthenticationProvider
) {
ensureClient(authProvider);
try {
let response: PageCollection = await graphClient!.api('/users').get();
// let allUsers: User[] = [];
let callback: PageIteratorCallback = (data) => {
console.log('file: GraphService.tsx ~ line 129 ~ data', data);
return true;
};
let pageIterator = new PageIterator(graphClient!, response, callback);
await pageIterator.iterate();
} catch (e) {
throw e;
}
That works wonders!
Thank you all for the help