0

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

  • I imagine that `req` is the request of the corresponding framework. You need to tell TypeScript about the type(s): See [this](https://stackoverflow.com/questions/38900537/typescript-extend-express-session-interface-with-own-class) – Carlo Corradini Mar 02 '23 at 15:28
  • It's not that TypeScript doesn't know about the type of `req`. It even autocompletes to `userId`. But the type of userId inside my resolver is `number | undefined`. It should be just `number` because my middleware only runs the resolver if `userId` is not undefined – blackEagle Mar 02 '23 at 16:18
  • Leveraging the answer from https://stackoverflow.com/a/74049208/6676781, see [This Example](https://stackblitz.com/edit/cz5htb?file=index.ts&view=editor) – Carlo Corradini Mar 02 '23 at 17:06

0 Answers0