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 config
import wixData from 'wix-data';
const {google} = require("googleapis");
const SCOPES = ['https://www.googleapis.com/auth/calendar']; //the url of the api
let options = {
"suppressAuth": true //suppress db auth to allow secure db permissions
};
//-----------------------------Insert Client Config File Into Database----------------------------//
export async function client(config) {
let response = await wixData.query("config").eq('title', 'client config').find(options);
if (response.items.length === 0) {
const toInsert = {
"title": "client config",
"value": config
};
response = await wixData.insert("config", toInsert);
return;
}
let items = response.items;
let item = items[0];
let updated;
const toUpdate = {
"_id": item._id,
"title": "client config",
"value": config
};
return await wixData.update("config", toUpdate, options);
}
//-----------------------------Get Link For Access Token----------------------------//
export async function getAuthUrl() {
const oAuth2Client = await createClient();
const res = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
})
return Promise.resolve(res);
}
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;
}
//-----------------------------Generate Tokens For Accessing Google Calendar API----------------------------//
export async function generateTokens(offlineCode) {
const authClient = await createClient();
return authClient.getToken(offlineCode, async (err, tokenJson) => {
if (err) {
console.log(err);
} else {
let response = await wixData.query("config").eq('title', 'refresh token').find(options);
if (response.items.length === 0) {
const toInsert = {
"title": "refresh token",
"value": JSON.stringify(tokenJson)
};
response = await wixData.insert("config", toInsert);
return;
}
let items = response.items;
let item = items[0];
const toUpdate = {
"_id": item._id,
"title": "refresh token",
"value": JSON.stringify(tokenJson)
};
const ret = await wixData.update("config", toUpdate, options);
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment