var calendarId = process.env.GOOGLE_CALENDAR_ID; var calendarEventsUrl = 'https://www.googleapis.com/calendar/v3/calendars/' + calendarId + '/events'; router.post('/addEvent', function(req, res, next) { var event = { summary: req.body.summary, description: req.body.description, attendees: [ { email: 'seattlelegalcalendar@gmail.com' } ], start: { dateTime: moment(startDate).format("YYYY-MM-DDTHH:mm:ssZ"), timeZone: timezonePST }, end: { dateTime: moment(endDate).format("YYYY-MM-DDTHH:mm:ssZ"), timeZone: timezonePST } }; executeOAuthRequest(calendarEventsUrl, event, next, function(body) { // send a success response }); });
You can see the basic structure of the body of a create event request. It has a summary, the description and the start and end dates. I used moment.js to properly format the date so that is understood by Google's Calendar API.
Then it calls the helper method that I showed on my last post to get the access token and make the request:
function executeOAuthRequest(url, body, next, successCallback) { tokenProvider.getToken(function (err, token) { var requestOptions = { url: url, json: true, method: 'POST', body: body, auth: { 'bearer': token } }; request(requestOptions, function (error, response, body) { if (error) { console.log('Failed to send request', error); next(error); } else if (response.statusCode !== 200) { console.log('Response is not have a 200 OK.', response.statusCode, body); next(new Error('Invalid status code.')); } else { successCallback(body, response); } }); }); }
To make the request I used the request npm package and as can be seen, the request options includes the authentication bearer token set to the OAuth access token that was retrieved. The POST is sent to the Calendar API passing the event object from before and all that's left is to handle any possible errors. The screen recording below shows the full experience on the client.
In the next post we will wrap up by adding some validation to the route handler before sending the request. In the mean time the source code is available at bitbucket or you can play with the live test site.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.