I had created a CurrentUser() decorator for my grapqhl mutation:
import {createParamDecorator, ExecutionContext} from "@nestjs/common"
import {getReqFromAutoContext} from "../../util/auto-context-request"
export const CurrentUser = createParamDecorator(
(_data: unknown, context: ExecutionContext) => {
return getReqFromAutoContext(context).user
},
)
Where getReqFromAutoContext simply switches on the contextType:
import {GqlContextType, GqlExecutionContext} from "@nestjs/graphql"
import {ExecutionContext} from "@nestjs/common"
export const getReqFromAutoContext = (context: ExecutionContext) => {
const contextType = context.getType<GqlContextType>()
if (contextType === "ws") {
return context.switchToWs().getClient().request
} else if (contextType === "http") {
return context.switchToHttp().getRequest()
} else if (contextType === "graphql") {
return GqlExecutionContext.create(context).getContext().req
} else if (contextType === "rpc") {
return context.switchToRpc().getContext().req
} else {
throw new Error(`Unknown context type: ${contextType}`)
}
}
For some reason, req was always undefined, which seems to be related to the block-scope create, getContext and .req are called or accessed in. I do not assume this is expected behaviour, but has anyone had something similar happen before?