この記事では、「Microsoft Graph を使用して JavaScript アプリをビルドする」で作成したアプリケーション と、Microsoft Graph ユーザー API を使用したアプリ専用認証を拡張します。 Microsoft Graph を使用して、organization内のユーザーを一覧表示します。
graphHelper.js 開き、次の関数を追加します。
export async function getUsersAsync() { // Ensure client isn't undefined if (!_appClient) { throw new Error('Graph has not been initialized for app-only auth'); } return _appClient ?.api('/users') .select(['displayName', 'id', 'mail']) .top(25) .orderby('displayName') .get(); }index.jsの空の
listUsersAsync関数 を 次のように置き換えます。async function listUsersAsync() { try { const userPage = await getUsersAsync(); const users = userPage.value; // Output each user's details for (const user of users) { console.log(`User: ${user.displayName ?? 'NO NAME'}`); console.log(` ID: ${user.id}`); console.log(` Email: ${user.mail ?? 'NO EMAIL'}`); } // If @odata.nextLink is not undefined, there are more users // available on the server const moreAvailable = userPage['@odata.nextLink'] != undefined; console.log(`\nMore users available? ${moreAvailable}`); } catch (err) { console.log(`Error getting users: ${err}`); } }アプリを実行し、オプション 2 を選択してユーザーを一覧表示します。
[1] Display access token [2] List users [3] Make a Graph call [0] Exit Select an option [1...3 / 0]: 2 User: Adele Vance ID: 05fb57bf-2653-4396-846d-2f210a91d9cf Email: AdeleV@contoso.com User: Alex Wilber ID: a36fe267-a437-4d24-b39e-7344774d606c Email: AlexW@contoso.com User: Allan Deyoung ID: 54cebbaa-2c56-47ec-b878-c8ff309746b0 Email: AllanD@contoso.com User: Bianca Pisani ID: 9a7dcbd0-72f0-48a9-a9fa-03cd46641d49 Email: NO EMAIL User: Brian Johnson (TAILSPIN) ID: a8989e40-be57-4c2e-bf0b-7cdc471e9cc4 Email: BrianJ@contoso.com ... More users available? true
コードの説明
getUsersAsync関数のコードについて考えてみましょう。
- ユーザーのコレクションを取得します
-
selectを使用して特定のプロパティを要求します -
topを使用して、返されるユーザーの数を制限します -
orderByを使用して応答を並べ替える