首页 > 解决方案 > 我的 firebaseUser 在 apollo 客户端的 onError 函数中为空

问题描述

我的设置是带有 apollo 客户端和 firebase auth 的 nextJS。1小时后,我得到了graphqlError“auth/token-expired”,所以我想要执行firebase函数来获取新令牌,但我的用户在onError函数中为null。我究竟做错了什么?

    const apolloClient = (param) => {
    let { loggedIn } = nookies.get(param?.ctx, null)
    const httpLink = createUploadLink({ uri: constants.gqlServer });
    const errorLink = onError(({ response, operation, graphQLErrors, forward }) => {
        if (graphQLErrors) {

            for (let err of graphQLErrors) {
                switch (err.extensions.code) {
                    case "auth/id-token-expired":
                        console.log(operation)
                        firebase.auth().onIdTokenChanged(user => {
                            if (user) {
                                user.getIdToken().then(function (accessToken) {
                                    nookies.set(param.ctx, "loggedIn", accessToken, { path: "/" })
                                    operation.setContext(({ headers = {} }) => ({
                                        headers: {
                                            // Re-add old headers
                                            ...headers,
                                            // Switch out old access token for new one
                                            authorization: `Bearer ${accessToken}`|| null
                                        }
                                    }));

                                    forward(operation)
                                });

                            } else {
                                nookies.destroy(param.ctx, "loggedIn")
                                nookies.destroy(param.ctx, "uid")
                                nookies.destroy(param.ctx, "startupCheck")
                                handleLogOut()
                                // nookies.destroy(null, "url")
                            }
                        });

                    // nookies.destroy(param.ctx, "loggedIn")
                    // nookies.destroy(param.ctx, "uid")
                    // nookies.destroy(param.ctx, "startupCheck")
                    // response.errors = null;
                }
            }
        }
    })
    const authLink = setContext(async (req, { headers }) => {
        return {
            headers: {
                ...headers,
                authorization: loggedIn ? `Bearer ${loggedIn}` : null,
            },
        };
    });

    return new ApolloClient({
        ssrMode: typeof window === "undefined",
        link: ApolloLink.from([
            errorLink,
            authLink.concat(httpLink),
        ]),
        credentials: "include",
        cache: new InMemoryCache(),
    })
}

标签: reactjsfirebasegraphqlnext.jsapollo-client

解决方案


推荐阅读