Estou a aceder ao calendário do google api, e tenho uma configuração lambda num asny try catch. Eu tentei adicionar espera a cada função, tentei mover o retorno para depois do if(err) mas isso me dá um 500. O que eu preciso fazer é passar os dados do array da função api do calendário do google para a mensagem para que eu possa obtê-lo no meu front end. Aqui está a lambda até agora. Qualquer ajuda seria muito apreciada. Obrigado
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() }
}
}
Este é o fetch que estou a fazer para ele na parte da frente e ele devolve um objecto vazio
const IndexPage = () => {
fetch(/functions/list-calendar)
.then(response => response.json())
.then(response => {
console.log(response)
})