Node/Apollo/GraphQL - 在 Apollo Server 插件中使用 async/await 的建议

问题描述

关于在 apollo 插件中使用 async/await 有什么建议吗?我正在尝试等待 twilio 服务承诺并遇到 Can not use keyword 'await' outside an async function babel 解析器错误并且不确定如何将父函数转换为异步。这是基本布局:

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);
                        }
                    }
                }
            }
        },}
};

上面的代码抛出了 BABEL_PARSE_ERROR。我尝试了多种方法将异步添加willSendResponse 和/或 requestDidStart,但结果不一。作为参考,以下是我实例化 ApolloServer 的方法

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(),]
})

解决方法

不是 async 的函数是你的函数。只需在您的 async 上添加 willSendResponse。这是一种方法:

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);
                        }
                    }
                }
            }
        },}
};