Newer
Older
import { Module, UnauthorizedException } from '@nestjs/common';
import { PrismaModule } from './prisma/prisma.module';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { ResolverModule } from './resolvers/resolver.module';
import { Context } from 'graphql-ws';
GraphQLModule.forRootAsync<ApolloDriverConfig>({
inject: [ModuleRef],
useFactory: (ref: ModuleRef) => ({
driver: ApolloDriver,
autoSchemaFile: true,
playground: true,
subscriptions: {
'graphql-ws': {
onConnect: (context: Context<any, any>) => {
const { connectionParams, extra } = context;
const token = connectionParams.authorization;
if (!token)
throw new UnauthorizedException(
'Missing token in websocket auth',
);
extra.token = token;
},
context: (ctx) => {
if (ctx.req) return { req: ctx.req, ref };
if (ctx.request) return { req: ctx.request, ref };
const token = ctx?.extra?.token;
return {
req: {
headers: {
authorization: token,
},
ref,
};
},
}),