I am hitting the google calendar api, and I have a lambda setup in a async try catch. I have tried adding await to every function, tried moving the return to after the if(err) but that gives me a 500. What I need to do is pass the array data from the google calendar api function to the message so I can get it in my front end. Here is the lambda so far. Any help would be greatly appreciated. Thanks
const { google } = require("googleapis")
const { OAuth2 } = google.auth
const faunadb = require("faunadb") /* Import faunaDB sdk */
// Docs on event and context https://www.netlify.com/docs/functions/#the-handler-method
exports.handler = async (event, context) => {
try {
const OAuth2Client = new OAuth2(
"FDSAF",
"FDSAF"
)
// Connect to the database
const q = faunadb.query
const client = new faunadb.Client({
secret: "FDSAFA",
})
let refreshToken
await client
.query(q.Get(q.Ref(q.Collection("AuthUrl"), "fdsa")))
.then(ret => (refreshToken = ret.data.title.refresh_token))
console.log(refreshToken)
OAuth2Client.setCredentials({
refresh_token: refreshToken,
})
// Create a new calender instance.
const calendar = google.calendar({ version: "v3", auth: OAuth2Client })
let ok
function listEvents(callback) {
let array = []
calendar.events.list(
{
calendarId: "primary",
// timeMin: new Date().toISOString(),
maxResults: 100000,
singleEvents: true,
orderBy: "startTime",
},
(err, res) => {
if (err) return console.log("The API returned an error: " + err)
var date = new Date()
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1)
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0)
//console.log(res.data.items)
const events = res.data.items
if (events.length) {
// console.log("Upcoming 10 events:")
events.map((event, i) => {
const start = new Date(event.start.dateTime || event.start.date)
const end = new Date(event.end.dateTime || event.end.date)
if (start >= firstDay && end <= lastDay) {
console.log(start, end, event.summary)
//ok = "test"
array.push(start)
callback(array)
}
// const start = event.start.dateTime || event.start.date
// console.log(`${start} - ${event.summary}`)
})
} else {
console.log("No upcoming events found.")
}
}
)
}
let array
listEvents(function (eventList) {
array = eventList
})
return {
statusCode: 200,
body: JSON.stringify({ message: array }),
// // more keys you can return:
// headers: { "headerName": "headerValue", ... },
// isBase64Encoded: true,
}
} catch (err) {
return { statusCode: 500, body: err.toString() }
}
}
This is the fetch I am doing for it on the front end and it returns an empty object
const IndexPage = () => {
fetch("/functions/list-calendar")
.then(response => response.json())
.then(response => {
console.log(response)
})