google calenderID nodejs 不适用于指定的 CalendarID

google calenderID nodejs doesn't work with specified CalendarID

我想使用 google 日历,如果我选择的日历 ID 不是主要的而是指定的,我会在 line 46 (const eventsArray = res.data.calendars.calID.busy) 中收到一条错误消息。错误消息看起来像这样 (node:49993) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'calendar' of undefined。所以基本上,我相信,它无法读取日历 ID,任何人都可以帮我找出我的错吗?

const { google } = require('googleapis');
    const { OAuth2 } = google.auth;
    const oAuth2Client = new OAuth2(
        'id_works_with_primary_calender', 
        'key_works_with_primary_calender'
    )
    
    oAuth2Client.setCredentials({
        refresh_token: 
            'works_with_primary',
    })
    
    const calendar = google.calendar( { version: 'v3', auth: oAuth2Client } );
    
    const eventStartTime = new Date()
    eventStartTime.setDate(eventStartTime.getDay() + 2)
    
    const eventEndTime = new Date()
    eventEndTime.setDate(eventEndTime.getDay() + 2)
    eventEndTime.setMinutes(eventEndTime.getMinutes() + 45)
    
    const event = {
        summary: 'Meet with David',
        location: '295 California St, San Francisco, CA 94111',
        description: 'Meeting with David to talk about the new client Project and drink some stuff',
        colorId: 1,
        start: {
            dateTime: eventStartTime,
            timeZone: 'Europe/Zurich',
        },
        end: {
            dateTime: eventEndTime,
            timeZone: 'Europe/Zurich',
        },
    }
    
    calendar.freebusy.query( {
        resource: {
            timeMin: eventStartTime,
            timeMax: eventEndTime,
            timeZone: 'Europe/Zurich',
        items: [ { id: 'gd3q30fhkprf0ubsk3pnqkc64k@group.calendar.google.com' } ],
        },
    }, (err, res) => {
        if (err) return console.error('Free Busy Query Error: ', err)
        //Here is the error    
        const eventsArray = res.data.calendars.gd3q30fhkprf0ubsk3pnqkc64k@group.calendar.google.com.busy
        if(eventsArray.length === 0)
            return calendar.events.insert( { 
                calendarId: 'gd3q30fhkprf0ubsk3pnqkc64k@group.calendar.google.com',
                resource: event,
            },
            err => {
                if (err) return console.error('Calender Event Creation: ' + err)
                    return console.log('Event Created: ' + event)    
        })
        return console.log("I'm Busy")
    })

问题:

问题似乎是 id 包含几个点,程序认为这些点用于访问嵌套属性。因此,它正在寻找 id gd3q30fhkprf0ubsk3pnqkc64k@group 的 属性 calendar,当然,它没有找到它,因为正确的 id 是 gd3q30fhkprf0ubsk3pnqkc64k@group.calendar.google.com.

解决方案:

因此,假设 idres.data.calendars 返回,应该通过更改访问 key 属性 的语法来解决问题, 从点符号到括号符号。

也就是说,替换成这个:

const eventsArray = res.data.calendars.gd3q30fhkprf0ubsk3pnqkc64k@group.calendar.google.com.busy

有了这个:

const eventsArray = res.data.calendars["gd3q30fhkprf0ubsk3pnqkc64k@group.calendar.google.com"].busy

参考: