filipstefansson / nexus-validate

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

Accept yup validate options #19

Closed JoosepAlviste closed 2 years ago

JoosepAlviste commented 2 years ago

Hey, thanks a lot for this library!

Currently, only the first validation error is returned in the GraphQL response, because Yup aborts early (default abortEarly value is true in validate arguments). I would like to receive all errors (basically, pass in abortEarly: false to validate).

This PR makes it so that custom params can be passed to the validate function. This way, the caller can pass in any validate function options to Yup.

Now, I can pass in abortEarly: false so that all validation errors would be returned instead of only the first one. It's worth noting that in that case, I also need to use a custom formatError function to correctly return the nested errors.

If you're interested, I need to customize the `formatError` like so: ```ts type UserInputErrorInner = { message: string path?: string } class AppUserInputError extends UserInputError { inner: UserInputErrorInner[] = [] constructor( message: string, extensions: { invalidArgs: string[] code?: string }, inner: UserInputErrorInner[] = [], ) { super(message, extensions) this.inner = inner } } // Plugin config... validatePlugin({ yupValidateOptions: { abortEarly: false, }, formatError: ({ error }: ValidatePluginErrorConfig) => { if (!(error instanceof ValidationError)) { return error } const errors = error.inner.length ? error.inner : [error] return new AppUserInputError( error.message, { invalidArgs: error.path ? [error.path] : [] }, errors.map((e) => ({ message: e.message, path: e.path, })), ) }, }), ```

Let me know what you think!