Matt Larsuma
Matt Larsuma

Reputation: 1519

Node/Apollo/GraphQL - advice on using async/await in an Apollo Server plugin

Any advice on using async/await in an apollo plugin? I'm attempting to await a twilio service promise and running into the Can not use keyword 'await' outside an async function babel parser error and unsure how to convert the parent function to be async. Here's the basic layout:

export const twilioVerification = async () => {
    return {
        requestDidStart () {
            return {
                willSendResponse ({ operationName, response, context }) {
                    if (['UpdateUser', 'CreateUser', 'SignInByPhone'].includes(operationName)) {
                        const user = response.data[operationName];
                        if (user != null) {
                            await sendVerificationText(user.phoneNumber);
                        }
                    }
                }
            }
        },
    }
};

The above code throws the BABEL_PARSE_ERROR. I've attempted a variety of ways to add async to willSendResponse and/or requestDidStart with mixed unsuccessful results. For reference, here's how I am instantiating ApolloServer as well:

const server = new ApolloServer({
  context: { driver, neo4jDatabase: process.env.NEO4J_DATABASE },
  schema: schema,
  introspection: process.env.APOLLO_SERVER_INTROSPECTION,
  playground: process.env.APOLLO_SERVER_PLAYGROUND,
  plugins: [
    pushNotifications(firebase),
    twilioVerification(),
  ]
})

Upvotes: 1

Views: 1014

Answers (1)

Dan Crews
Dan Crews

Reputation: 3637

The function that isn't async is your function. Just add async on your willSendResponse. Here is one way to do that:

export const twilioVerification = async () => {
    return {
        requestDidStart () {
            return {
                willSendResponse: async ({ operationName, response, context }) => {
                    if (['UpdateUser', 'CreateUser', 'SignInByPhone'].includes(operationName)) {
                        const user = response.data[operationName];
                        if (user != null) {
                            await sendVerificationText(user.phoneNumber);
                        }
                    }
                }
            }
        },
    }
};

Upvotes: 1

Related Questions