如何从 getServerSideProps 中提取查询以分离帮助文件?

How to extract query from `getServerSideProps` to separate helper file?

我有几个页面想在 getServerSideProps 中调用查询来请求当前用户。

我目前的情况是这样的:

import { NextPageContext } from 'next';
import { withAuth } from 'hoc/withAuth';
import { addApolloState, initializeApollo } from 'lib/apolloClient';
import { MeDocument } from 'generated/types';
import nookies from 'nookies';
import Profile from 'components/Profile';

const ProfilePage: React.FC = () => <Profile />;

export const getServerSideProps = async (
  context: NextPageContext
): Promise<any> => {
  // withAuth(context);

  const client = initializeApollo();
  const { my_token } = nookies.get(context);

  await client.query({
    query: MeDocument,
    context: {
      headers: {
        authorization: my_token ? `Bearer ${my_token}` : '',
      },
    },
  });

  return addApolloState(client, { props: {} });
};

export default ProfilePage;

这有效,我可以在我的 Apollo devtools 中验证缓存正在与用户一起更新。

当我尝试将 Apollo 初始化和查询移动到一个单独的文件中时,由于某种原因缓存从未更新。

withAuth.tsx 文件中,我有这样的东西:

import { NextPageContext } from 'next';
import { addApolloState, initializeApollo } from 'lib/apolloClient';
import { MeDocument } from 'generated/types';
import nookies from 'nookies';

export const withAuth = async (context: any,) => {
  const client = initializeApollo();
  const { gc_token } = nookies.get(context);

  await client.query({
    query: MeDocument,
    context: {
      headers: {
        authorization: gc_token ? `Bearer ${gc_token}` : '',
      },
    },
  });

  return addApolloState(client, { props: {} });
};

有了这个,我所要做的就是在getServerSideProps中调用withAuth()。没有错误,但是缓存没有更新。

如何将该代码正确提取到单独的文件中?

感谢@juliomalves 的评论,我只是忘了 return withAuth 函数!

现在是这样的:

pages/index.tsx

export const getServerSideProps = async (
  context: NextPageContext
): Promise<any> => await withAuth(context);

withAuth.tsx

/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { getSession } from 'next-auth/client';
import redirectToLogin from 'helpers/redirectToLogin';
import { addApolloState, initializeApollo } from 'lib/apolloClient';
import { MeDocument } from 'generated/types';
import nookies from 'nookies';

export const withAuth = async (context: any) => {
  const session = await getSession(context);
  const isUser = !!session?.user;

  // no authenticated session
  if (!isUser) redirectToLogin();

  const client = initializeApollo();
  const { token } = nookies.get(context);

  await client.query({
    query: MeDocument,
    context: {
      headers: {
        authorization: token ? `Bearer ${token}` : '',
      },
    },
  });

  return addApolloState(client, { props: {} });
};