Hook fails when async
I'm trying to call an external API when a new user is created, to setup a "subaccount" on twilio for them. My function works fine if I execute it synchronously, but as soon as I await the resolution or return a promise, it fails.
This works fine:
'use latest'
const twilio = require('twilio')
const { TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN } = process.env
module.exports = async (event) => {
console.log(event)
const client = twilio(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
try {
const email = event.data.email
const subaccount = client.api.accounts.create({ friendlyName: email })
console.log('Created subaccount', subaccount)
} catch (err) {
console.error(err)
return { error: 'Twilio subaccount setup failed' }
}
return event
}
But of course I don't actually have the subaccount value, so I can't store the new account number. Instead subaccount is {status: 'pending'}, a pending promise. Once I add the await keyword, the function fails and the graphcool console shows the error:
const subaccount = await client.api.accounts.create({ friendlyName: email })
{"error":"Function returned invalid status code: 0. Raw body: empty.last"}
I tried executing this function manually via the node REPL (passing a fake event object) and it works fine.
I've also tried removing async/await and having the function return a promise:
'use latest'
const twilio = require('twilio')
const { TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN } = process.env
module.exports = (event) => {
console.log(event)
const client = twilio(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
const email = event.data.email
return client.api.accounts.create({ friendlyName: email })
.then((subaccount) => {
console.log('Created subaccount', subaccount)
return event
})
.catch((err) => {
console.error(err)
return { error: 'Twilio subaccount setup failed' }
})
}
Which throws the same error. I also tried renaming the file .ts and using import/export instead of require/module.exports but that also failed with the same error.
Maybe this is user error, but I can't tell from that log. Maybe I shouldn't be using an operationAfter hook. Any advice?
Is this a Framework project? Could you try without 'use latest', and provide a complete service definition for reproduction purposes?
I was using an operationAfter hook (also tried operationBefore). Switching to a subscription solved the issue for me and is a better alternative for this use case anyway. I don't have this problem anymore nor a working reproduction, so I'm happy to close the issue, or I can try to reproduce with a fresh project if that would be helpful. Let me know what you think.
Thanks @timwis, I'm closing this for now. Feel free to create another report when you can reproduce it again 👍
I'm getting the same issue using the pusher template. Removing async/await doesn't change anything.
Can you please create a new bug report with reproduction information, @ylac?