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.36k stars 164 forks source link

Add context object to validator function #716

Open RobbeCl opened 1 year ago

RobbeCl commented 1 year ago

Would it be possible to access the context object inside a validator function? I want to access the userId inside the context, but I do not have access to it.

hayes commented 1 year ago

can you elaborate a bit on the use case here?

Unfortunately I don't think this is easy to do with the current version of the plugin. I will eventually be writing a new validation plugin (likely along side pothos@4, which is a long ways out) that supports some new use cases.

The issue with the current approach is that it basically compiles all the validators for a field down into a zod schema when the schema is created, args are then fed into the validator at run time, but because all the validation functions have already been handed off to zod, they can't be passed the context anymore. Unfortunately, I think fixing this would basically require re-writing the plugin from scratch

RobbeCl commented 1 year ago

Yeah I took a dive into the code and since pothos is using Zod as the core validator, it would not be simple to pass those arguments. See this as a feature request :-)

vimutti77 commented 5 months ago

My use case is that I need to check that the argument can be used by the current login user.

e.g.

const UpdateUserInput = builder.inputType('UpdateUserInput', {
  fields: (t) => ({
    positionId: t.string({
      validate: {
        refine: async (val, ctx) => {
          const result = await canPositionBeUsedByUser({ positionId: val, userId: ctx.userId })
          return result
        },
      },
    }),
  }),
})