SSR getServerSideProps上的next.js graphql上下文为空{}

时间:2020-10-26 12:42:22

标签: next.js

我的页面上有getServerSideProps:

export const getServerSideProps: GetServerSideProps = async (ctx) => {
  const apolloClient = initializeApollo()

  await apolloClient.query({
    query: UserQuery,
    variables: { id: Number(ctx.query.id) },
  })

  return {
    props: { initialApolloState: apolloClient.cache.extract() },
  }
}

用户的解析器:

resolve: async (_parent, { where }, ctx, info) => {
 const select = new PrismaSelect(info).value

 console.log(ctx) // {} why is empty when i use getServerSideProps?

 const res = await ctx.db.user.findOne({
    where: { id: 1 },
    ...select,
 })

 return null
},

相同的客户端查询工作正常,但是由于某些原因,当我使用getServerSideProps时ctx为空。该如何解决?

我可以将ctx传递给const apolloClient = initializeApollo(null, ctx),但是它将不会运行具有db属性的apolloServer ctx解析器功能,并且ctx.db将是未定义的。


Apollo服务器:

const apolloServer = new ApolloServer({
  schema,
  async context(ctx: Ctx): Promise<Ctx> {
    ctx.db = prisma

    return ctx
  },
})

export const apolloServerHandler = apolloServer.createHandler({ path: '/api/graphql' })

Apollo客户端:

import { useMemo } from 'react'
import { ApolloClient, InMemoryCache, NormalizedCacheObject } from '@apollo/client'
import { IncomingMessage, ServerResponse } from 'http'

type ResolverContext = {
  req?: IncomingMessage
  res?: ServerResponse
}

const typePolicies = {
  Test: {
    keyFields: ['id'],
  },
  User: {
    keyFields: ['id'],
  },
}

let apolloClient: ApolloClient<NormalizedCacheObject>

function createIsomorphLink(context: ResolverContext = {}): any {
  if (typeof window === 'undefined') {
    const { SchemaLink } = require('@apollo/client/link/schema')
    const { schema } = require('backend/graphql/schema')
    return new SchemaLink({ schema, context })
  } else {
    const { HttpLink } = require('@apollo/client/link/http')
    return new HttpLink({
      uri: '/api/graphql',
      credentials: 'same-origin',
    })
  }
}

function createApolloClient(context?: ResolverContext): ApolloClient<NormalizedCacheObject> {
  return new ApolloClient({
    ssrMode: typeof window === 'undefined',
    link: createIsomorphLink(context),
    cache: new InMemoryCache({ typePolicies }),
  })
}

export function initializeApollo(
  initialState: any = null,
  // Pages with Next.js data fetching methods, like `getStaticProps`, can send
  // a custom context which will be used by `SchemaLink` to server render pages
  context?: ResolverContext
): ApolloClient<NormalizedCacheObject> {
  const _apolloClient = apolloClient ?? createApolloClient(context)

  // If your page has Next.js data fetching methods that use Apollo Client, the initial state
  // get hydrated here
  if (initialState) {
    // Get existing cache, loaded during client side data fetching
    const existingCache = _apolloClient.extract()
    // Restore the cache using the data passed from getStaticProps/getServerSideProps
    // combined with the existing cached data
    _apolloClient.cache.restore({ ...existingCache, ...initialState })
  }
  // For SSG and SSR always create a new Apollo Client
  if (typeof window === 'undefined') return _apolloClient
  // Create the Apollo Client once in the client
  if (!apolloClient) apolloClient = _apolloClient

  return _apolloClient
}

// eslint-disable-next-line
export function useApollo(initialState: any): ApolloClient<NormalizedCacheObject> {
  const store = useMemo(() => initializeApollo(initialState), [initialState])
  return store
}

1 个答案:

答案 0 :(得分:1)

您需要应用上下文解析器:

async contextResolver(ctx: Ctx): Promise<Ctx> {
    ctx.db = prisma

    return ctx
 },

const apolloServer = new ApolloServer({
  schema,
  context: contextResolver,
})

在getServerSideProps内部:

export const getServerSideProps: GetServerSideProps = async (ctx) => {
  await contextResolver(ctx)
  const apolloClient = initializeApollo(null, ctx)

  await apolloClient.query({
    query: UserQuery,
    variables: { id: Number(ctx.query.id) },
  })

  return {
    props: { initialApolloState: apolloClient.cache.extract() },
  }
}