Skip to content

Instantly share code, notes, and snippets.

@shanwixcode
Last active Jun 28, 2020
Embed
What would you like to do?
Wix Code - Google Calendar API Backend File 2
import wixData from 'wix-data';
const {google} = require("googleapis");
let options = {
"suppressAuth": true //suppress db auth to allow secure db permissions
};
export async function insertNewEvent(summary, location, description, start, end, attendees) {
const authorizedAuthClient = await createAuthorizedClient();
return insertRow(authorizedAuthClient, summary, location, description, start, end, attendees);
}
//--------------------------------------------Create Authorized Client-----------------------------------------------//
async function createAuthorizedClient() {
try {
const oAuth2Client = await createClient();
let tokens = await getTokens();
oAuth2Client.setCredentials(tokens);
const tokensRes = await oAuth2Client.refreshAccessToken(tokens);
oAuth2Client.getTokenInfo(tokensRes); // checks validity of tokens
return oAuth2Client;
} catch (err) {
console.log("failed to refreh token" + err);
}
}
export async function createClient() {
let val = await getClientConfig();
let credentials = JSON.parse(val);
const { client_secret, client_id, redirect_uris } = credentials.installed;
return new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
}
export async function getClientConfig() {
const response = await wixData.query("config").eq('title', 'client config').find(options);
if(response.items.length === 0) return null;
return response.items[0].value;
}
//--------------------------------------------Create Access Token to validate the api call to Google-----------------------------------------------//
export async function getTokens() {
const response = await wixData.query("config").eq('title', 'refresh token').find(options);
if(response.items.length === 0) return null;
return JSON.parse(response.items[0].value);
}
//--------------------------------------------Insert the new event-----------------------------------------------//
function insertRow(authorizedAuthClient, summary, location, description, start, end, attendees) {
const calendar = google.calendar('v3');
const event = {
'summary': summary,
'location': location,
'description': description,
'start': {
'dateTime': start
},
'end': {
'dateTime': end
},
'attendees': [
attendees
],
'reminders': {
'useDefault': true
}
};
try {
return calendar.events.insert({
auth: authorizedAuthClient,
calendarId: 'primary',
resource: event,
},
function (err, response) {
if (err) {
console.log("error in append:" + err);
return;
}
return "ok";
});
} catch (err) {
console.log("error in append values" + err);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment