hayes / pothos

Pothos GraphQL is library for creating GraphQL schemas in typescript using a strongly typed code first approach
https://pothos-graphql.dev
ISC License
2.28k stars 153 forks source link

How do I use relayMutationField & authField/withAuth work together? #1211

Open KaisSalha opened 1 month ago

KaisSalha commented 1 month ago

Basically how do I make those 2 work together:


Context: ContextType; // { user?: User; }

AuthContexts: {
    isAuthenticated: ContextType & { user: User };
};

authScopes: ({ isAuthenticated }) => ({
    isAuthenticated,
}),

builder.relayMutationField(
    "updateUser",
    {
        inputFields: (t) => ({
            first_name: t.string({ required: false }),
            last_name: t.string({ required: false }),
            avatar_url: t.string({ required: false }),
        }),
    },
    {
        authScopes: {
            isAuthenticated: true,
        },
        resolve: async (_root, args, ctx) => {
            try {
                const updateFields: Partial<UserType> = {
                    ...(args.input.first_name && {
                        first_name: args.input.first_name,
                    }),
                    ...(args.input.last_name && {
                        last_name: args.input.last_name,
                    }),
                    ...(args.input.avatar_url && {
                        avatar_url: args.input.avatar_url,
                    }),
                };

                const [user] = await db
                    .update(users)
                    .set(updateFields)
                    .where(eq(users.id, ctx.user.id)) // ctx.user could be undefined
                    .returning();

                return {
                    success: true,
                    user,
                };
            } catch (error) {
                console.log(error);
                return {
                    success: false,
                };
            }
        },
    },
    {
        outputFields: (t) => ({
            success: t.boolean({
                resolve: (result) => result.success,
            }),
            user: t.field({
                type: User,
                nullable: true,
                resolve: (result) => result.user,
            }),
        }),
    }
);
hayes commented 1 month ago

Unfortunately these methods just aren't compatible. You can define auth scopes, but you won't be able to get the updated context type when using relayMutationField

KaisSalha commented 1 month ago

Thanks for the quick reply.