简体   繁体   中英

How to get calender's events by calendar name, with Microsoft-Graph and NodeJS?

How can I make this one API call? This code uses microsoft-graph-client to make two api calls. The frist call gets the ID of the calender I want. The second uses the calendar's ID to get the events of that calendar. Would like to have one API call. All the documentation I have read so far does not have ability to get calendar events of a specified calendar.

//// Modules used... 
var authHelper = require('../helpers/auth'); //// used to get the access token
var graph = require('@microsoft/microsoft-graph-client'); 

...

//// Initialize Graph client with access token.
const client = graph.Client.init({
  authProvider: (done) => {
    done(null, accessToken);
  }
});
//// Specify start and end times for second API call.
const start = new Date(new Date().setHours(0,0,0));
const end = new Date(new Date(start).setDate(start.getDate() + 30000));


  /**
   * Step 1
   *   Get all the calendar, then cut out the calendar id I need.
   * STEP 2
   *   Get the events using the calendar id.
   */
  const calendars = await client 
      .api('https://graph.microsoft.com/v1.0/me/calendars/')      
      .select('name,id')    
      .get();
  /**
   * Cut out the id of first calendar named 'School_Calendar' in the array of calendars.
   */
  const c = calendars.value.find(obj => {
    return obj.name === 'School_Calendar'
  });
  const calen_id = c.id;      

  /**
   * Now use the Calendar's id to get the calendar's events. 
   */
  const api = `/me/calendars/${calen_id}/calendarView?startDateTime=${start.toISOString()}&endDateTime=${end.toISOString()}`;
  const result = await client
      .api(api)      
      .select('subject,start,end')
      .orderby('start/dateTime DESC')
      .get();

  //// print the events of School_Calendar
  console.log(result.value;);

That's doable since calendar could be addressed by id and its name like this:

GET /me/calendars/{id|name}

where name corresponds to a Calendar.name property

Hence events could retrieved via a single request like this:

GET /me/calendars/{name}/calendarView?startDateTime={start_datetime}&endDateTime={end_datetime}

Example

const data = await client
      .api(
        `/users/${userId}/calendars/${calName}/calendarView?startDateTime=${start.toISOString()}&endDateTime=${end.toISOString()}`
      )
      .get()
const events = data.value;
for (let event of events) {
    //...
}       

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM