Custom typing GlobalContext

Hey team,

I’m adding the request IP address in my redwood lambda gql api like so:

type ContextFunctionArgs = {
  context: { event: APIGatewayProxyEvent; ipAddress?: string }
}

const ipAddress = (args: ContextFunctionArgs) => {
  const ipAddress = args?.context?.event?.requestContext?.identity?.sourceIp
  if (!ipAddress) {
    throw new Error('Could not extract users IP address.')
  }
  return ipAddress
}
const setContext: ContextFunction = async (args: ContextFunctionArgs) => {
  args.context.ipAddress = ipAddress(args)
  return args.context
}

export const handler = createGraphQLHandler({
  authDecoder,
  getCurrentUser,
  loggerConfig: { logger, options: {} },
  directives,
  sdls,
  services,
  armorConfig: { maxDepth: { n: 10 } },
  onException: () => {
    // Disconnect from your database with an unhandled exception.
    db.$disconnect()
  },
  context: setContext,
  cors: {
    origin: corsOrigins,
    credentials: true,
  },
})

I’ve tried adding a custom type declaration like so:

declare module '@redwoodjs/graphql-server' {
  interface GlobalContext {
    ipAddress?: string
  }
}

But this confuses typescript and the GlobalContext now doesn’t have any types, including currentUser which is there by default.

Is there something that I’m missing or is this not supported by redwood atm?

Not sure if you found an answer. GlobalContext is a Redwood-defined type. When you use the declare module syntax to define an ambient module, you’re replacing what’s already defined. I think you could import the type and extend your custom type (with the ipAddress key) from it, something like:

import type { GlobalContext as RWGlobalContext } from "@redwoodjs/graphql-server"

declare module '@redwoodjs/graphql-server' {
  interface GlobalContext extends RWGlobalContext {
    ipAddress?: string
  }
}

I didn’t test it to see if it works.