I have a resolver for creating posts and adding the authorId as a foreign key from my session.
@Mutation(() => PostType)
@UseMiddleware(isAuth)
async createPost(
@Arg('title') title: string,
@Arg('text') text: string,
@Ctx() { prisma, req }: MyContext
): Promise<PostType> {
return await prisma.post.create({
data: {
title,
text,
authorId: req.session.userId,
},
});
}
But typescript says that my userId on req.session may be undefined, even though I have an useMiddleware decorator with the isAuth function which looks like this
import { MyContext } from 'src/types';
import { MiddlewareFn } from 'type-graphql';
export const isAuth: MiddlewareFn<MyContext> = ({ context }, next) => {
console.log('isAuth middleware: ', context.req.session.userId);
if (context.req.session.userId === undefined) {
throw new Error('Not authenticated');
}
return next();
};
When I add the if block inside my resolver it works. I know I could also just // @ts-ignore
or cast req.session.userId as number
but I don't know if there is another way to fix this