0

Learning GraphQL and a bit stuck with passing req into a generate context function I made to keep things neat.

I think I am doing something dumb with the line createContext((req) => req) as if I console.log( ctx.request ) in a route handler I get [Function (anonymous)]

Whats an alternative way to capture the this.req from the server.ts scope and pass it into createContext?

server.ts

import { ApolloServer } from 'apollo-server'
import { schema } from './nexusSchema'
import { createContext } from './context'

const server = new ApolloServer({
  schema,
  context: createContext((req) => req),
})

server.listen().then(({ url }) => {
  console.log(`  Server ready at ${url}`)
})

context.ts

import { PrismaClient, Prisma as PrismaTypes } from '@prisma/client'
import { PrismaDelete, onDeleteArgs } from '@paljs/plugins'
import { PubSub } from 'apollo-server'

class Prisma extends PrismaClient {
  constructor(options?: PrismaTypes.PrismaClientOptions) {
    super(options)
  }

  async onDelete(args: onDeleteArgs) {
    const prismaDelete = new PrismaDelete(this)
    await prismaDelete.onDelete(args)
  }
}

const prisma = new Prisma()
const pubsub = new PubSub()

export interface Context {
  prisma: Prisma
  select: any
  pubsub: PubSub
  request: {
    request: {
      headers: {
        authorization: string
      }
    }
    connection: {
      context: {
        Authorization: string
      }
    }
  }
}

export function createContext(req): Context {
  return {
    prisma,
    select: {},
    pubsub,
    request: req,
  }
}
user3234810
  • 482
  • 2
  • 5
  • 18

1 Answers1

0

I was being dumb after all.

Note, I also had to adjust the interface for the request object to suit Apollo Server 2!

server.ts

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

context.ts

export interface Context {
  prisma: Prisma
  select: any
  pubsub: PubSub
  request: {
    req: {
      headers: {
        authorization: string
      }
    }
    connection: {
      context: {
        Authorization: string
      }
    }
  }
}

export const createContext = (req): Context => {
  return {
    prisma,
    select: {},
    pubsub,
    request: req,
  }
}
user3234810
  • 482
  • 2
  • 5
  • 18