0

这是我目前的设置。但是对于这个设置,我无法在解析器中访问 prisma 客户端。这里的目标是在所有解析器中访问上下文及其类型。下面的代码包含我的 server.ts 文件内容和 context.ts 文件内容。我在这里想念什么?

server.ts 文件

import { schema } from './schema'
import { context } from './context'

//auth context 
const authContext = async ({ req }: { req: Request }) => {
  let authUser = {}
  const token = (req.headers && req.headers.authorization) || ''

  if (token !== null) {
    try {
      const payload: any = verify(token, authConfig.JWT.JWT_SECRET_1!)
      authUser = payload.user
    } catch (error) {
      console.log(error)
    }
  }
  return {
    authUser,
    context,
  }
}

export const server = new ApolloServer({
  schema,
  context: authContext,
})

server.listen({ port: appConfig.port }).then(async ({ url }) => {
  console.log(` Server ready at: ${url}${appConfig.graphqlPath}`)
})

上下文.ts

import { PrismaClient, User } from '@prisma/client'
import { SmsAPI } from './datasources/SMS/SmsAPI'
import { typesSMS } from './datasources/SMS/typeDefs'

export interface Context {
  prisma: PrismaClient
  authUser: Pick<User, 'id' | 'nidNumber'>
  dataSources: {
    smsAPI: typesSMS
  }
}

// datasource instance
export const prisma = new PrismaClient({
  log: ['query', 'error'],
})

// prisma instance
export const dataSources = () => ({
  smsAPI: new SmsAPI()
})

export const context: Context = {
  prisma: prisma,
  authUser: { id: 0, nidNumber: '' },
  dataSources: {
    smsAPI: dataSources,
  },
}
4

0 回答 0