filipstefansson / nexus-validate

🔑 Add argument validation to your GraphQL Nexus API.
35 stars 8 forks source link

feat: add support for generic validations through input objects #9

Closed filipstefansson closed 1 year ago

filipstefansson commented 3 years ago

What this PR is about

Adds support for generic validations through inputObjectType. The validate method here needs to return a function that returns an ObjectShape instead of a function, because we can't pass args and context here:

export const UserInput = inputObjectType({
  name: 'UserInput',
  definition(t) {
    t.string('email');
  },
  validate: ({ string }) => ({
    email: string().email().required(),
  }),
});

This will then get called whenever UserInput is used.

Work left to do

A field currently only support one validation function, and since yup schemas can't be merged we will need to support passing an array of validation functions so we can call all of them. Today, this scenario wouldn't work:

t.list.field('friends', {
  type: User,
  args: {
    name: stringArg(),
    query: arg({
      type: UserInput,
    }),
  },
  // this would be overwritten by the validation in UserInput
  validate: ({ string }) => ({ name: string().min(10) }),
});

The idea is that our resolver should be able to run both validations.

Blockers

The implementation works, but the types are currently broken and needs this PR to work: https://github.com/graphql-nexus/nexus/pull/799

patryk-smc commented 3 years ago

That would be nice to have! Even without merging validate functions. Do you need help with getting this shipped?

filipstefansson commented 3 years ago

@patryk-smc That would be great, thanks!

ysfaran commented 2 years ago

I like that feature!

You actually can merge yup schemas using concat() for extending or shape() overriding object() schemas. Few examples can be found in this ticket: jquense/yup#232 For this library it would probably make sense to use concat() to merge two (or more) schemas.

I played arround with it a little bit and it actually worked for the most part as expected.

I also opened an issue in yup's repo because there seems to be a bug when chaining optional() and required(): jquense/yup#1535

assimovt commented 2 years ago

this is a great addition @filipstefansson I'm also trying to use it with the inputObjectType.

Looks like https://github.com/graphql-nexus/nexus/pull/799 has been merged. What's currently missing to get this one main? 🎉

ysfaran commented 1 year ago

Is this project actively maintained? I would also love this feature.