微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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);
                        }
                    }
                }
            }
        },}
};

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。