【问题标题】:Node/Apollo/GraphQL - advice on using async/await in an Apollo Server pluginNode/Apollo/GraphQL - 关于在 Apollo 服务器插件中使用 async/await 的建议
【发布时间】:2021-06-01 02:57:37
【问题描述】:

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

【问题讨论】:

    标签: node.js express graphql apollo apollo-server


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-11-07
      • 2020-12-25
      • 2020-09-30
      • 2021-05-09
      • 2019-11-15
      • 2019-02-03
      • 2020-09-11
      • 2020-12-21
      • 2021-10-04
      相关资源
      最近更新 更多